import { auth } from '@/services/auth';

export interface IToken {
  accessToken: string;
  refreshToken: string;
  expiresAt: string;
}

export interface IUser {
  avatarUrl: string;
  email: string | null;
  id: string;
  nickname: string;
  phone: string | null;
  platforms: string[];
  status: number;
  unifiedUserId: string;
}

/**
 * 模板信息接口 - 匹配后端Template抽象类
 */
export interface Template {
  code: string; // 模板唯一标识码
  name: string; // 模板名称
  description: string; // 模板详细描述
  creditCost: number; // 积分消耗
  version?: string; // 版本号
  inputExampleUrl?: string; // 原始图片示例
  outputExampleUrl?: string; // 输出图片示例
  tags: string[]; // 标签数组
  templateType: 'IMAGE' | 'VIDEO'; // 模板类型：图片或视频
  workflow?: string; // 工作流名称
  isActive: boolean; // 是否激活
  stripeProductId?: string; // Stripe产品ID
  stripePriceId?: string; // Stripe价格ID
  imageModel?: string; // 图片模型（如dall-e-3）
  imagePrompt?: string; // 图片生成提示词
  createdAt?: string; // 创建时间
  lastStripeSyncAt?: string; // 最后同步Stripe时间
  imageCount?: number; // 图片数量
}

/**
 * API 响应基础接口 - 匹配后端NestJS控制器的响应格式
 */
interface ApiResponse<T = any> {
  success?: boolean; // 请求是否成功
  code: number; // 状态码
  message?: string; // 响应消息
  msg?: string; // 兼容旧版本消息字段
  data: T; // 响应数据
  timestamp?: string; // 时间戳
  traceId?: string; // 链路追踪ID
}

/**
 * 模板执行参数
 */
export interface ExecuteTemplateParams {
  templateCode: string; // 模板代码
  imageUrl: string; // 图片URL
}

/**
 * 模板执行结果
 */
export interface ExecuteTemplateResult {
  executionId: string; // 执行ID
  taskId: string; // 任务ID
  status: 'pending' | 'running' | 'completed' | 'failed'; // 任务状态
}

/**
 * 任务执行进度信息
 */
export interface TaskProgress {
  taskId: string; // 任务ID
  executionId: string; // 执行ID
  status: 'pending' | 'running' | 'completed' | 'failed'; // 任务状态
  progress: number; // 进度百分比 (0-100)
  result?: {
    videoUrl?: string; // 生成的视频URL
    imageUrl?: string; // 生成的图片URL
  };
  createdAt: string; // 创建时间
  completedAt?: string; // 完成时间
}

/**
 * 支付会话创建参数
 */
export interface CreateCheckoutParams {
  templateCode: string; // 模板代码
  metadata: {
    imageUrls: string[]; // 图片URL
    cb_url: string;
    [key: string]: any; // 其他元数据
  };
}

/**
 * 支付会话结果
 */
export interface CheckoutSessionResult {
  sessionId: string; // Stripe会话ID
  url: string; // 支付页面URL
  paymentId: string; // 内部支付ID
}

/**
 * 支付历史记录
 */
export interface PaymentHistory {
  id: string; // 支付ID
  templateCode: string; // 模板代码
  status: 'pending' | 'completed' | 'failed' | 'cancelled' | 'refunded'; // 支付状态
  amount: number; // 金额（分）
  currency: string; // 货币类型
  createdAt: string; // 创建时间
}

/**
 * 退款参数
 */
export interface RefundParams {
  reason: 'user_request' | 'technical_issue' | 'duplicate' | 'fraudulent'; // 退款原因
  amount?: number; // 退款金额（分），不指定则全额退款
  metadata?: {
    note?: string; // 退款说明
    [key: string]: any; // 其他元数据
  };
}

/**
 * Google OAuth用户信息
 */
export interface GoogleUserInfo {
  id: string; // Google用户ID
  email: string; // 邮箱
  name: string; // 姓名
  picture?: string; // 头像URL
  customerId?: string;
  created?: boolean;
}

/**
 * OAuth令牌刷新参数
 */
export interface RefreshTokenParams {
  refresh_token: string; // 刷新令牌
  user_id?: string; // 用户ID（可选）
}

/**
 * OAuth令牌响应
 */
export interface TokenResponse {
  access_token: string; // 访问令牌
  expires_in: number; // 过期时间（秒）
  scope?: string; // 权限范围
  refresh_token?: string; // 刷新令牌
}

/**
 * 创建任务参数
 */
export interface CreateTaskParams {
  type: 'video_generation' | 'image_generation'; // 任务类型
  templateCode: string; // 模板代码
  userId?: string; // 用户ID
  parameters: {
    imageUrl: string; // 图片URL
    [key: string]: any; // 其他参数
  };
}

/**
 * 用户执行历史
 */
export interface UserExecution {
  executionId: string; // 执行ID
  templateCode: string; // 模板代码
  status: 'pending' | 'running' | 'completed' | 'failed'; // 状态
  createdAt: string; // 创建时间
  result?: {
    videoUrl?: string; // 生成的视频URL
    imageUrl?: string; // 生成的图片URL
  };
}

/**
 * 批量操作参数
 */
export interface BulkOperationParams {
  templateCodes: string[]; // 模板代码数组
  operation: 'sync_stripe' | 'activate' | 'deactivate'; // 操作类型
}

/**
 * 模板同步状态
 */
export interface TemplateSyncStatus {
  code: string; // 模板代码
  name: string; // 模板名称
  isActive: boolean; // 是否激活
  hasStripeProduct: boolean; // 是否有Stripe产品
  lastStripeSyncAt?: string; // 最后同步时间
}

/**
 * Mixvideo Workflow SDK客户端
 * 用于与Mixvideo Workflow API进行通信，支持：
 * - 模板管理（创建、更新、删除、激活、禁用）
 * - 支付处理（Stripe集成、结账、退款）
 * - 任务管理（视频生成、进度追踪）
 * - Google OAuth认证（登录、令牌刷新、撤销）
 *
 * @example
 * const sdk = new SdkServer('https://api.bestaibest.ai');
 * const templates = await sdk.getAllTemplates();
 */
export class SdkServer {
  private readonly baseUrl: string; // API基础URL
  private readonly timeout: number; // 请求超时时间（毫秒）

  /**
   * 初始化SDK客户端
   * @param url API基础URL，默认为Mixvideo Workflow的生产环境
   * @param timeout 请求超时时间（毫秒），默认5分钟
   */
  constructor(url: string = `https://api.bestaibest.ai`, timeout: number = 5 * 60 * 1000) {
    this.baseUrl = url.endsWith('/') ? url.slice(0, -1) : url;
    this.timeout = timeout;
  }

  /**
   * 发送HTTP请求的通用方法
   * 支持自动重试、错误处理、认证头部添加
   * @param url 请求路径
   * @param method HTTP方法
   * @param data 请求数据
   * @param retryCount 当前重试次数
   * @returns API响应数据
   */
  private async request<T>(url: string, method: 'GET' | 'POST' = 'GET', data?: any, retryCount: number = 0): Promise<ApiResponse<T>> {
    const maxRetries = 3;
    const retryDelay = 1000 * (retryCount + 1); // 递增延迟

    try {
      console.log(`🚀 SDK Server request: ${method} ${this.baseUrl}${url}`, { data, retryCount });

      const requestConfig: any = {
        url: `${this.baseUrl}${url}`,
        method,
        timeout: this.timeout,
        header: {
          'Content-Type': 'application/json',
          Accept: 'application/json',
          // 强制使用HTTP/1.1避免HTTP/2问题
          Connection: 'keep-alive',
          Authorization: `Bearer ${auth.getAccessToken()}`,
        },
        // 禁用HTTP/2
        enableHttp2: false,
        // 启用缓存
        enableCache: false,
      };

      // 根据请求方法设置数据
      if (method === 'GET') {
        // GET请求使用query参数
        if (data) {
          const params = new URLSearchParams(data).toString();
          requestConfig.url += `?${params}`;
        }
      } else {
        // POST请求使用body
        requestConfig.data = data;
      }

      const response = await fetch(requestConfig.url, {
        method: requestConfig.method,
        headers: requestConfig.header,
        body: requestConfig.method === 'POST' ? JSON.stringify(requestConfig.data) : undefined,
        mode: 'cors',
      });

      const responseData = await response.json();

      console.log(`✅ SDK Server response:`, {
        status: response.status,
        data: responseData,
        headers: response.headers,
      });

      if (response.ok) {
        const apiResponse = responseData as ApiResponse<T>;

        // 检查API响应状态
        if (apiResponse.success || apiResponse.code === 200) {
          return apiResponse;
        }
        throw new Error(apiResponse.message || apiResponse.msg || 'API request failed');
      } else if (response.status === 401) {
        await auth.login();
        throw new Error('Unauthorized');
      } else {
        throw new Error(`HTTP ${response.status}: ${responseData?.msg || 'Request failed'}`);
      }
    } catch (error: any) {
      // 检查是否是网络错误且可以重试
      const isNetworkError =
        error.message?.includes('fetch') || error.message?.includes('timeout') || error.message?.includes('network') || error.name === 'TypeError';

      if (isNetworkError && retryCount < maxRetries) {
        console.log(`♾️ Retrying request in ${retryDelay}ms... (${retryCount + 1}/${maxRetries})`);
        await new Promise(resolve => setTimeout(resolve, retryDelay));
        return this.request<T>(url, method, data, retryCount + 1);
      }

      // 包装错误信息
      const errorMessage = error.message || 'Unknown network error';
      throw new Error(`😫 网络请求失败: ${errorMessage}`);
    }
  }

  // ==================== 模板管理相关接口 ====================

  /**
   * 获取所有活跃模板列表
   * GET /templates
   */
  async getAllTemplates(): Promise<Template[]> {
    const response = await this.request<{ templates: Template[]; total: number }>('/templates');
    return response.data.templates || [];
  }

  /**
   * 根据模板代码获取单个模板信息
   * GET /templates/get/:code
   */
  async getTemplate(templateCode: string): Promise<Template | null> {
    try {
      const response = await this.request<Template>(`/templates/get/${templateCode}`);
      return response.data;
    } catch (error) {
      console.warn(`Template ${templateCode} not found:`, error);
      return null;
    }
  }

  /**
   * 执行模板工作流
   * POST /templates/execute/:code
   */
  async executeTemplate(params: ExecuteTemplateParams): Promise<ExecuteTemplateResult> {
    try {
      const response = await this.request<ExecuteTemplateResult>(`/templates/execute/${params.templateCode}`, 'POST', {
        // userId: params.userId,
        imageUrl: params.imageUrl,
      });
      return response.data;
    } catch (error) {
      throw error;
    }
  }
  /**
   * 如果多图的话 images.join(',')
   */
  async payTemplateCode(templateCode: string, imageUrls: string[], cbUrl: string) {
    try {
      const response = await this.request(`/payment/checkout/${templateCode}`, 'POST', {
        imageUrls: imageUrls, // 图片URL
        cb_url: cbUrl,
      });
      return response.data as { url: string };
    } catch (error) {
      throw error;
    }
  }

  /**
   * 创建新模板
   * POST /templates
   */
  async createTemplate(template: Partial<Template>): Promise<{ code: string; stripeProductId: string; stripePriceId: string }> {
    try {
      const response = await this.request<{ code: string; stripeProductId: string; stripePriceId: string }>('/templates', 'POST', template);
      return response.data;
    } catch (error) {
      throw error;
    }
  }

  /**
   * 更新模板信息
   * PUT /templates/update/:code
   */
  async updateTemplate(templateCode: string, updates: Partial<Template>): Promise<{ updated: boolean; stripeSynced: boolean }> {
    try {
      const response = await this.request<{ updated: boolean; stripeSynced: boolean }>(`/templates/update/${templateCode}`, 'POST', updates);
      return response.data;
    } catch (error) {
      throw error;
    }
  }

  /**
   * 删除模板
   * DELETE /templates/delete/:code
   */
  async deleteTemplate(templateCode: string): Promise<{ deleted: boolean }> {
    try {
      const response = await this.request<{ deleted: boolean }>(`/templates/delete/${templateCode}`, 'POST');
      return response.data;
    } catch (error) {
      throw error;
    }
  }

  /**
   * 激活模板并同步到Stripe
   * POST /templates/activate/:code
   */
  async activateTemplate(templateCode: string): Promise<{ isActive: boolean; stripeSynced: boolean }> {
    try {
      const response = await this.request<{ isActive: boolean; stripeSynced: boolean }>(`/templates/activate/${templateCode}`, 'POST');
      return response.data;
    } catch (error) {
      throw error;
    }
  }

  /**
   * 禁用模板
   * POST /templates/deactivate/:code
   */
  async deactivateTemplate(templateCode: string): Promise<{ isActive: boolean; stripeSynced: boolean }> {
    try {
      const response = await this.request<{ isActive: boolean; stripeSynced: boolean }>(`/templates/deactivate/${templateCode}`, 'POST');
      return response.data;
    } catch (error) {
      throw error;
    }
  }

  /**
   * 同步模板到Stripe
   * POST /templates/sync/:code
   */
  async syncTemplateToStripe(
    templateCode: string,
    forceUpdate = false
  ): Promise<{ synced: boolean; stripeProductId: string; stripePriceId: string }> {
    try {
      const response = await this.request<{ synced: boolean; stripeProductId: string; stripePriceId: string }>(
        `/templates/sync/${templateCode}`,
        'POST',
        {
          forceUpdate,
        }
      );
      return response.data;
    } catch (error) {
      throw error;
    }
  }

  /**
   * 批量操作模板
   * POST /templates/bulk
   */
  async bulkOperationTemplates(params: BulkOperationParams): Promise<{ successful: string[]; failed: string[]; total: number }> {
    try {
      const response = await this.request<{ successful: string[]; failed: string[]; total: number }>('/templates/bulk', 'POST', params);
      return response.data;
    } catch (error) {
      throw error;
    }
  }

  /**
   * 同步所有模板到Stripe
   * GET /templates/sync-all-stripe
   */
  async syncAllTemplatesToStripe(): Promise<{ successful: number; failed: number; total: number }> {
    try {
      const response = await this.request<{ successful: number; failed: number; total: number }>('/templates/sync-all-stripe');
      return response.data;
    } catch (error) {
      throw error;
    }
  }

  /**
   * 检查模板-Stripe同步状态
   * GET /templates/sync-status
   */
  async getTemplateSyncStatus(): Promise<{
    totalTemplates: number;
    withStripeProduct: number;
    activeTemplates: number;
    needsSync: number;
    templates: TemplateSyncStatus[];
  }> {
    try {
      const response = await this.request<{
        totalTemplates: number;
        withStripeProduct: number;
        activeTemplates: number;
        needsSync: number;
        templates: TemplateSyncStatus[];
      }>('/templates/sync-status');
      return response.data;
    } catch (error) {
      throw error;
    }
  }

  /**
   * 验证模板Stripe同步状态
   * GET /templates/verify-sync/:code
   */
  async verifyTemplateSync(templateCode: string): Promise<{
    templateCode: string;
    synced: boolean;
    issues: string[];
    stripeProductId?: string;
    stripePriceId?: string;
    recommendations: string[];
  }> {
    try {
      const response = await this.request<{
        templateCode: string;
        synced: boolean;
        issues: string[];
        stripeProductId?: string;
        stripePriceId?: string;
        recommendations: string[];
      }>(`/templates/verify-sync/${templateCode}`);
      return response.data;
    } catch (error) {
      throw error;
    }
  }

  /**
   * 诊断Stripe环境和配置
   * GET /templates/diagnose-stripe
   */
  async diagnoseStripe(): Promise<{ environment: string; apiKeyValid: boolean; issues: string[]; accountInfo: any; recommendations: string[] }> {
    try {
      const response = await this.request<{
        environment: string;
        apiKeyValid: boolean;
        issues: string[];
        accountInfo: any;
        recommendations: string[];
      }>('/templates/diagnose-stripe');
      return response.data;
    } catch (error) {
      throw error;
    }
  }

  /**
   * 模板服务健康检查
   * GET /templates/health
   */
  async getTemplateHealth(): Promise<{ totalTemplates: number; timestamp: string; service: string }> {
    try {
      const response = await this.request<{ totalTemplates: number; timestamp: string; service: string }>('/templates/health');
      return response.data;
    } catch (error) {
      throw error;
    }
  }

  /**
   * 初始化模板数据
   * GET /templates/init
   */
  async initTemplates(): Promise<{
    total: number;
    imported: number;
    failed: number;
    details: Array<{ code: string; status: string; error?: string }>;
  }> {
    try {
      const response = await this.request<{
        total: number;
        imported: number;
        failed: number;
        details: Array<{ code: string; status: string; error?: string }>;
      }>('/templates/init');
      return response.data;
    } catch (error) {
      throw error;
    }
  }

  /**
   * 创建测试模板
   * POST /templates/test/create
   */
  async createTestTemplate(): Promise<{ code: string; stripeProductId: string; stripePriceId: string }> {
    try {
      const response = await this.request<{ code: string; stripeProductId: string; stripePriceId: string }>('/templates/test/create', 'POST');
      return response.data;
    } catch (error) {
      throw error;
    }
  }

  /**
   * 登录 (H5版本暂时简化)
   * @param params
   * @returns
   */
  async login(params: any): Promise<{ tokens: IToken; user: IUser }> {
    try {
      const response = await this.request<{ tokens: IToken; user: IUser }>(`/login`, 'POST', {
        platform: 'h5',
        ...params,
      });
      return response.data;
    } catch (error) {
      throw error;
    }
  }

  /**
   * 获取用户信息 可检测token是否过期（兼容方法）
   * @returns
   */
  async profile(): Promise<GoogleUserInfo> {
    try {
      const response = await this.request<GoogleUserInfo>('/auth/google/customer');
      return response.data;
    } catch (error) {
      throw error;
    }
  }

  /**
   * 批量获取指定模板
   */
  async getTemplatesByCodes(templateCodes: string[]): Promise<Template[]> {
    const templates: Template[] = [];
    for (const code of templateCodes) {
      try {
        const template = await this.getTemplate(code);
        if (template) {
          templates.push(template);
        }
      } catch (error) {
        console.warn(`Failed to get template ${code}:`, error);
      }
    }
    return templates;
  }

  /**
   * 获取执行进度
   * GET /templates/execution/:taskId/progress
   */
  async getTaskProgress(taskId: string): Promise<TaskProgress> {
    try {
      console.log(`🎨 Getting task progress for: ${taskId}`);
      const response = await this.request<TaskProgress>(`/templates/execution/${taskId}/progress`);
      console.log(`📊 Task progress response:`, response.data);
      return response.data;
    } catch (error) {
      throw error;
    }
  }
  /**
   * 获取用户执行历史
   * GET /templates/executions/user/:userId
   */
  async getUserExecutions(): Promise<UserExecution[]> {
    try {
      const uid = auth.getUserId();
      if (!uid) {
        throw new Error('用户ID不存在');
      }
      const response = await this.request<{ executions: UserExecution[]; total: number }>(`/templates/executions/user`);
      return response.data.executions || [];
    } catch (error) {
      throw error;
    }
  }

  /**
   * 获取我的执行日志（兼容方法）
   */
  async getMineLogs(): Promise<UserExecution[]> {
    return this.getUserExecutions();
  }

  // ==================== 支付相关接口 ====================

  /**
   * 创建Stripe结账会话
   * POST /payment/checkout/:templateCode
   */
  async createCheckoutSession(params: CreateCheckoutParams): Promise<CheckoutSessionResult> {
    try {
      const response = await this.request<CheckoutSessionResult>(`/payment/checkout/${params.templateCode}`, 'POST', params.metadata);
      return response.data;
    } catch (error) {
      throw error;
    }
  }

  /**
   * 处理支付成功回调
   * GET /payment/success
   */
  async handlePaymentSuccess(sessionId: string, paymentId: string): Promise<{ payment: any; execution: ExecuteTemplateResult }> {
    try {
      const response = await this.request<{ payment: any; execution: ExecuteTemplateResult }>('/payment/success', 'GET', {
        session_id: sessionId,
        payment_id: paymentId,
      });
      return response.data;
    } catch (error) {
      throw error;
    }
  }

  /**
   * 处理支付取消
   * GET /payment/cancel
   */
  async handlePaymentCancel(sessionId: string, paymentId: string): Promise<{ payment: any }> {
    try {
      const response = await this.request<{ payment: any }>('/payment/cancel', 'GET', {
        session_id: sessionId,
        payment_id: paymentId,
      });
      return response.data;
    } catch (error) {
      throw error;
    }
  }

  /**
   * 获取用户支付历史
   * GET /payment/history
   */
  async getPaymentHistory(userId: string): Promise<{ payments: PaymentHistory[]; total: number }> {
    try {
      const response = await this.request<{ payments: PaymentHistory[]; total: number }>('/payment/history', 'GET', {
        userId,
      });
      return response.data;
    } catch (error) {
      throw error;
    }
  }

  /**
   * 处理退款
   * POST /payment/refund/:paymentId
   */
  async processRefund(paymentId: string, params: RefundParams): Promise<{ refundId: string; amount: number; status: string }> {
    try {
      const response = await this.request<{ refundId: string; amount: number; status: string }>(`/payment/refund/${paymentId}`, 'POST', params);
      return response.data;
    } catch (error) {
      throw error;
    }
  }

  /**
   * 获取支付详情
   * GET /payment/:paymentId
   */
  async getPaymentDetails(paymentId: string): Promise<any> {
    try {
      const response = await this.request<any>(`/payment/${paymentId}`);
      return response.data;
    } catch (error) {
      throw error;
    }
  }

  /**
   * 支付服务健康检查
   * GET /payment/health
   */
  async getPaymentHealth(): Promise<{ timestamp: string; service: string }> {
    try {
      const response = await this.request<{ timestamp: string; service: string }>('/payment/health');
      return response.data;
    } catch (error) {
      throw error;
    }
  }

  // ==================== 任务管理相关接口 ====================

  /**
   * 获取任务状态和详情
   * GET /task/:taskId
   */
  async getTaskDetails(taskId: string): Promise<TaskProgress> {
    try {
      const response = await this.request<TaskProgress>(`/task/${taskId}`);
      return response.data;
    } catch (error) {
      throw error;
    }
  }

  /**
   * 创建新任务
   * POST /task
   */
  async createTask(params: CreateTaskParams): Promise<string> {
    try {
      const response = await this.request<string>('/task', 'POST', params);
      return response.data;
    } catch (error) {
      throw error;
    }
  }

  /**
   * 使用指定ID创建任务
   * POST /task/:taskId
   */
  async createTaskWithId(taskId: string, params: Omit<CreateTaskParams, 'userId'>): Promise<string> {
    try {
      const response = await this.request<string>(`/task/${taskId}`, 'POST', params);
      return response.data;
    } catch (error) {
      throw error;
    }
  }

  // ==================== Google OAuth认证相关接口 ====================

  /**
   * 启动Google OAuth授权流程
   * GET /auth/google/authorize
   */
  generateGoogleAuthUrl(redirectUrl?: string, scopes?: string): string {
    const params = new URLSearchParams();
    if (redirectUrl) params.set('redirect_url', redirectUrl);
    if (scopes) params.set('scopes', scopes);

    const queryString = params.toString();
    return `${this.baseUrl}/auth/google/authorize${queryString ? '?' + queryString : ''}`;
  }

  /**
   * 刷新OAuth访问令牌
   * POST /auth/google/refresh
   */
  async refreshGoogleToken(params: RefreshTokenParams): Promise<TokenResponse> {
    try {
      const response = await this.request<TokenResponse>('/auth/google/refresh', 'POST', params);
      return response.data;
    } catch (error) {
      throw error;
    }
  }

  /**
   * 从google获取用户信息
   * GET /auth/google/userinfo
   */
  async getGoogleUserInfo(accessToken?: string): Promise<GoogleUserInfo> {
    try {
      const url = accessToken ? `/auth/google/userinfo?access_token=${accessToken}` : '/auth/google/userinfo';
      const response = await this.request<GoogleUserInfo>(url);
      return response.data;
    } catch (error) {
      throw error;
    }
  }

  /**
   * 撤销OAuth令牌
   * POST /auth/google/revoke
   */
  async revokeGoogleToken(token: string, userId?: string): Promise<void> {
    try {
      await this.request('/auth/google/revoke', 'POST', {
        token,
        user_id: userId,
      });
    } catch (error) {
      throw error;
    }
  }
}

export const api = new SdkServer();
