import path from 'path';
import { BasePlatformAdapter } from './base.js';
import type {
  AccountProfile,
  PublishParams,
  PublishResult,
  DateRange,
  AnalyticsData,
  CommentData,
} from './base.js';
import type { PlatformType, QRCodeInfo, LoginStatusResult } from '@media-manager/shared';
import { logger } from '../../utils/logger.js';
import { aiService } from '../../ai/index.js';

// Python 多平台发布服务配置
const PYTHON_PUBLISH_SERVICE_URL = process.env.PYTHON_PUBLISH_SERVICE_URL || process.env.XHS_SERVICE_URL || 'http://localhost:5005';

// 服务器根目录（用于构造绝对路径）
const SERVER_ROOT = path.resolve(process.cwd());

/**
 * 快手平台适配器
 */
export class KuaishouAdapter extends BasePlatformAdapter {
  readonly platform: PlatformType = 'kuaishou';
  readonly loginUrl = 'https://cp.kuaishou.com/';
  readonly publishUrl = 'https://cp.kuaishou.com/article/publish/video';
  
  protected getCookieDomain(): string {
    return '.kuaishou.com';
  }
  
  async getQRCode(): Promise<QRCodeInfo> {
    try {
      await this.initBrowser();
      
      if (!this.page) throw new Error('Page not initialized');
      
      await this.page.goto(this.loginUrl);
      await this.waitForSelector('.qrcode-img', 30000);
      
      const qrcodeImg = await this.page.$('.qrcode-img');
      const qrcodeUrl = await qrcodeImg?.getAttribute('src');
      
      if (!qrcodeUrl) {
        throw new Error('Failed to get QR code');
      }
      
      return {
        qrcodeUrl,
        qrcodeKey: `kuaishou_${Date.now()}`,
        expireTime: Date.now() + 300000,
      };
    } catch (error) {
      logger.error('Kuaishou getQRCode error:', error);
      throw error;
    }
  }
  
  async checkQRCodeStatus(qrcodeKey: string): Promise<LoginStatusResult> {
    try {
      if (!this.page) {
        return { status: 'expired', message: '二维码已过期' };
      }
      
      const currentUrl = this.page.url();
      
      if (currentUrl.includes('/profile') || currentUrl.includes('/article')) {
        const cookies = await this.getCookies();
        await this.closeBrowser();
        return { status: 'success', message: '登录成功', cookies };
      }
      
      return { status: 'waiting', message: '等待扫码' };
    } catch (error) {
      logger.error('Kuaishou checkQRCodeStatus error:', error);
      return { status: 'error', message: '检查状态失败' };
    }
  }
  
  async checkLoginStatus(cookies: string): Promise<boolean> {
    try {
      await this.initBrowser();
      await this.setCookies(cookies);
      
      if (!this.page) throw new Error('Page not initialized');
      
      await this.page.goto('https://cp.kuaishou.com/profile');
      await this.page.waitForLoadState('networkidle');
      
      const needLogin = await this.page.$('.login-btn');
      await this.closeBrowser();
      
      return !needLogin;
    } catch (error) {
      logger.error('Kuaishou checkLoginStatus error:', error);
      await this.closeBrowser();
      return false;
    }
  }
  
  async getAccountInfo(cookies: string): Promise<AccountProfile> {
    try {
      await this.initBrowser();
      await this.setCookies(cookies);
      
      if (!this.page) throw new Error('Page not initialized');
      
      await this.page.goto('https://cp.kuaishou.com/profile');
      await this.page.waitForLoadState('networkidle');
      
      const accountName = await this.page.$eval('.user-name', el => el.textContent?.trim() || '');
      const avatarUrl = await this.page.$eval('.avatar img', el => el.getAttribute('src') || '');
      
      await this.closeBrowser();
      
      return {
        accountId: '',
        accountName,
        avatarUrl,
        fansCount: 0,
        worksCount: 0,
      };
    } catch (error) {
      logger.error('Kuaishou getAccountInfo error:', error);
      await this.closeBrowser();
      throw error;
    }
  }
  
  /**
   * 检查 Python 发布服务是否可用
   */
  private async checkPythonServiceAvailable(): Promise<boolean> {
    try {
      const response = await fetch(`${PYTHON_PUBLISH_SERVICE_URL}/health`, {
        method: 'GET',
        signal: AbortSignal.timeout(3000),
      });
      if (response.ok) {
        const data = await response.json();
        return data.status === 'ok' && data.supported_platforms?.includes('kuaishou');
      }
      return false;
    } catch {
      return false;
    }
  }

  /**
   * 通过 Python 服务发布视频（带 AI 辅助）
   */
  private async publishVideoViaPython(
    cookies: string,
    params: PublishParams,
    onProgress?: (progress: number, message: string) => void
  ): Promise<PublishResult> {
    logger.info('[Kuaishou Python] Starting publish via Python service with AI assist...');
    onProgress?.(5, '正在通过 Python 服务发布...');

    try {
      // 将相对路径转换为绝对路径
      const absoluteVideoPath = path.isAbsolute(params.videoPath)
        ? params.videoPath
        : path.resolve(SERVER_ROOT, params.videoPath);

      const absoluteCoverPath = params.coverPath
        ? (path.isAbsolute(params.coverPath) ? params.coverPath : path.resolve(SERVER_ROOT, params.coverPath))
        : undefined;

      // 使用 AI 辅助发布接口
      const response = await fetch(`${PYTHON_PUBLISH_SERVICE_URL}/publish/ai-assisted`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          platform: 'kuaishou',
          cookie: cookies,
          title: params.title,
          description: params.description || params.title,
          video_path: absoluteVideoPath,
          cover_path: absoluteCoverPath,
          tags: params.tags || [],
          post_time: params.scheduledTime ? new Date(params.scheduledTime).toISOString().replace('T', ' ').slice(0, 19) : null,
          location: params.location || '重庆市',
          return_screenshot: true,
        }),
        signal: AbortSignal.timeout(600000),
      });

      const result = await response.json();
      logger.info('[Kuaishou Python] Response:', { ...result, screenshot_base64: result.screenshot_base64 ? '[截图已省略]' : undefined });

      // 使用通用的 AI 辅助处理方法
      return await this.aiProcessPythonPublishResult(result, undefined, onProgress);
    } catch (error) {
      logger.error('[Kuaishou Python] Publish failed:', error);
      throw error;
    }
  }

  async publishVideo(
    cookies: string,
    params: PublishParams,
    onProgress?: (progress: number, message: string) => void,
    onCaptchaRequired?: (captchaInfo: { taskId: string; type: 'sms' | 'image'; phone?: string; imageBase64?: string }) => Promise<string>,
    options?: { headless?: boolean }
  ): Promise<PublishResult> {
    // 只使用 Python 服务发布
    const pythonAvailable = await this.checkPythonServiceAvailable();
    if (!pythonAvailable) {
      logger.error('[Kuaishou] Python service not available');
      return {
        success: false,
        errorMessage: 'Python 发布服务不可用，请确保 Python 服务已启动',
      };
    }

    logger.info('[Kuaishou] Using Python service for publishing');
    try {
      const result = await this.publishVideoViaPython(cookies, params, onProgress);
      
      // 检查是否需要验证码
      if (!result.success && result.errorMessage?.includes('验证码')) {
        logger.info('[Kuaishou] Python detected captcha, need headful browser');
        return {
          success: false,
          errorMessage: `CAPTCHA_REQUIRED:${result.errorMessage}`,
        };
      }
      
      return result;
    } catch (pythonError) {
      logger.error('[Kuaishou] Python publish failed:', pythonError);
      return {
        success: false,
        errorMessage: pythonError instanceof Error ? pythonError.message : '发布失败',
      };
    }

    /* ========== Playwright 方式已注释，只使用 Python API ==========
    const useHeadless = options?.headless ?? true;

    try {
      await this.initBrowser({ headless: useHeadless });
      await this.setCookies(cookies);

      if (!this.page) throw new Error('Page not initialized');

      onProgress?.(5, '正在打开上传页面...');

      await this.page.goto(this.publishUrl, {
        waitUntil: 'domcontentloaded',
        timeout: 60000,
      });

      await this.page.waitForTimeout(3000);

      // 检查是否需要登录
      const currentUrl = this.page.url();
      if (currentUrl.includes('login') || currentUrl.includes('passport')) {
        await this.closeBrowser();
        return {
          success: false,
          errorMessage: '账号登录已过期，请重新登录',
        };
      }

      onProgress?.(10, '正在上传视频...');

      // 上传视频 - 优先使用 AI 截图分析找到上传入口
      let uploadTriggered = false;

      // 方法1: AI 截图分析找到上传入口
      logger.info('[Kuaishou Publish] Using AI to find upload entry...');
      try {
        const screenshot = await this.screenshotBase64();
        const guide = await aiService.getPageOperationGuide(screenshot, 'kuaishou', '找到视频上传入口并点击上传按钮');
        logger.info(`[Kuaishou Publish] AI analysis result:`, guide);

        if (guide.hasAction && guide.targetSelector) {
          logger.info(`[Kuaishou Publish] AI suggested selector: ${guide.targetSelector}`);
          try {
            const [fileChooser] = await Promise.all([
              this.page.waitForEvent('filechooser', { timeout: 10000 }),
              this.page.click(guide.targetSelector),
            ]);
            await fileChooser.setFiles(params.videoPath);
            uploadTriggered = true;
            logger.info('[Kuaishou Publish] Upload triggered via AI selector');
          } catch (e) {
            logger.warn(`[Kuaishou Publish] AI selector click failed: ${e}`);
          }
        }
      } catch (e) {
        logger.warn(`[Kuaishou Publish] AI analysis failed: ${e}`);
      }

      // 方法2: 尝试点击常见的上传区域触发 file chooser
      if (!uploadTriggered) {
        logger.info('[Kuaishou Publish] Trying common upload selectors...');
        const uploadSelectors = [
          // 快手常见上传区域选择器
          '[class*="upload-area"]',
          '[class*="upload-btn"]',
          '[class*="upload-video"]',
          '[class*="video-upload"]',
          '[class*="drag-upload"]',
          '.upload-trigger',
          '.video-uploader',
          'div[class*="uploader"]',
          'button:has-text("上传")',
          'div:has-text("上传视频"):not(:has(div))',
          'span:has-text("点击上传")',
          '[class*="add-video"]',
          '.kwai-upload',
        ];
        
        for (const selector of uploadSelectors) {
          if (uploadTriggered) break;
          try {
            const element = this.page.locator(selector).first();
            if (await element.count() > 0 && await element.isVisible()) {
              logger.info(`[Kuaishou Publish] Trying selector: ${selector}`);
              const [fileChooser] = await Promise.all([
                this.page.waitForEvent('filechooser', { timeout: 5000 }),
                element.click(),
              ]);
              await fileChooser.setFiles(params.videoPath);
              uploadTriggered = true;
              logger.info(`[Kuaishou Publish] Upload triggered via selector: ${selector}`);
            }
          } catch (e) {
            // 继续尝试下一个选择器
          }
        }
      }

      // 方法3: 直接设置 file input
      if (!uploadTriggered) {
        logger.info('[Kuaishou Publish] Trying file input method...');
        const fileInputs = await this.page.$$('input[type="file"]');
        logger.info(`[Kuaishou Publish] Found ${fileInputs.length} file inputs`);
        for (const fileInput of fileInputs) {
          try {
            const accept = await fileInput.getAttribute('accept');
            if (!accept || accept.includes('video') || accept.includes('*')) {
              await fileInput.setInputFiles(params.videoPath);
              uploadTriggered = true;
              logger.info('[Kuaishou Publish] Upload triggered via file input');
              break;
            }
          } catch (e) {
            logger.warn(`[Kuaishou Publish] File input method failed: ${e}`);
          }
        }
      }

      if (!uploadTriggered) {
        // 截图调试
        try {
          if (this.page) {
            const screenshotPath = `uploads/debug/kuaishou_no_upload_${Date.now()}.png`;
            await this.page.screenshot({ path: screenshotPath, fullPage: true });
            logger.info(`[Kuaishou Publish] Screenshot saved: ${screenshotPath}`);
          }
        } catch {}
        throw new Error('未找到上传入口');
      }

      // 等待上传完成
      onProgress?.(20, '视频上传中...');
      const maxWaitTime = 300000; // 5分钟
      const startTime = Date.now();

      while (Date.now() - startTime < maxWaitTime) {
        const progressText = await this.page.locator('[class*="progress"]').first().textContent().catch(() => '');
        if (progressText) {
          const match = progressText.match(/(\d+)%/);
          if (match) {
            const progress = parseInt(match[1]);
            onProgress?.(20 + Math.floor(progress * 0.4), `视频上传中: ${progress}%`);
          }
        }

        const uploadSuccess = await this.page.locator('.upload-success, [class*="success"], [class*="complete"]').count();
        if (uploadSuccess > 0) {
          logger.info('[Kuaishou Publish] Video upload completed');
          break;
        }

        await this.page.waitForTimeout(2000);
      }

      onProgress?.(60, '正在填写视频信息...');

      // 填写标题
      const titleInput = this.page.locator('.title-input, input[placeholder*="标题"]').first();
      if (await titleInput.count() > 0) {
        await titleInput.fill(params.title);
      }

      // 填写描述
      if (params.description) {
        const descInput = this.page.locator('.desc-input, textarea[placeholder*="描述"]').first();
        if (await descInput.count() > 0) {
          await descInput.fill(params.description);
        }
      }

      onProgress?.(80, '正在发布...');

      // 点击发布
      const publishBtn = this.page.locator('.publish-btn, button:has-text("发布")').first();
      if (await publishBtn.count() > 0) {
        await publishBtn.click();
      } else {
        throw new Error('未找到发布按钮');
      }

      // 等待发布结果
      onProgress?.(90, '等待发布完成...');
      const publishMaxWait = 120000; // 2分钟
      const publishStartTime = Date.now();
      let aiCheckCounter = 0;

      while (Date.now() - publishStartTime < publishMaxWait) {
        await this.page.waitForTimeout(3000);

        // 检查成功提示
        const successHint = await this.page.locator('.publish-success, [class*="success"]:has-text("成功")').count();
        if (successHint > 0) {
          onProgress?.(100, '发布成功！');
          await this.closeBrowser();
          return {
            success: true,
            videoUrl: this.page.url(),
          };
        }

        // 检查错误提示
        const errorHint = await this.page.locator('[class*="error"], [class*="fail"]').first().textContent().catch(() => '');
        if (errorHint && (errorHint.includes('失败') || errorHint.includes('错误'))) {
          throw new Error(`发布失败: ${errorHint}`);
        }

        // AI 辅助检测（每 3 次循环）
        aiCheckCounter++;
        if (aiCheckCounter >= 3) {
          aiCheckCounter = 0;
          const aiStatus = await this.aiAnalyzePublishStatus();
          if (aiStatus) {
            logger.info(`[Kuaishou Publish] AI status: ${aiStatus.status}, confidence: ${aiStatus.confidence}%`);

            if (aiStatus.status === 'success' && aiStatus.confidence >= 70) {
              onProgress?.(100, '发布成功！');
              await this.closeBrowser();
              return { success: true, videoUrl: this.page.url() };
            }

            if (aiStatus.status === 'failed' && aiStatus.confidence >= 70) {
              throw new Error(aiStatus.errorMessage || 'AI 检测到发布失败');
            }

            if (aiStatus.status === 'need_captcha' && onCaptchaRequired) {
              const imageBase64 = await this.screenshotBase64();
              try {
                const captchaCode = await onCaptchaRequired({
                  taskId: `kuaishou_captcha_${Date.now()}`,
                  type: 'image',
                  imageBase64,
                });
                if (captchaCode) {
                  const guide = await this.aiGetPublishOperationGuide('需要输入验证码');
                  if (guide?.hasAction && guide.targetSelector) {
                    await this.page.fill(guide.targetSelector, captchaCode);
                  }
                }
              } catch {
                logger.error('[Kuaishou Publish] Captcha handling failed');
              }
            }

            if (aiStatus.status === 'need_action' && aiStatus.nextAction) {
              const guide = await this.aiGetPublishOperationGuide(aiStatus.pageDescription);
              if (guide?.hasAction) {
                await this.aiExecuteOperation(guide);
              }
            }
          }
        }
      }

      // 超时，AI 最终检查
      const finalAiStatus = await this.aiAnalyzePublishStatus();
      if (finalAiStatus?.status === 'success') {
        onProgress?.(100, '发布成功！');
        await this.closeBrowser();
        return { success: true, videoUrl: this.page.url() };
      }

      throw new Error('发布超时，请手动检查是否发布成功');

    } catch (error) {
      logger.error('Kuaishou publishVideo error:', error);
      await this.closeBrowser();
      return {
        success: false,
        errorMessage: error instanceof Error ? error.message : '发布失败',
      };
    }
    ========== Playwright 方式已注释结束 ========== */
  }
  
  /**
   * 通过 Python API 获取评论
   */
  private async getCommentsViaPython(cookies: string, videoId: string): Promise<CommentData[]> {
    logger.info('[Kuaishou] Getting comments via Python API...');
    
    const response = await fetch(`${PYTHON_PUBLISH_SERVICE_URL}/comments`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        platform: 'kuaishou',
        cookie: cookies,
        work_id: videoId,
      }),
    });
    
    if (!response.ok) {
      throw new Error(`Python API returned ${response.status}`);
    }
    
    const result = await response.json();
    
    if (!result.success) {
      throw new Error(result.error || 'Failed to get comments');
    }
    
    // 转换数据格式
    return (result.comments || []).map((comment: {
      comment_id: string;
      author_id: string;
      author_name: string;
      author_avatar: string;
      content: string;
      like_count: number;
      create_time: string;
      reply_count: number;
      replies?: Array<{
        comment_id: string;
        author_id: string;
        author_name: string;
        author_avatar: string;
        content: string;
        like_count: number;
        create_time: string;
      }>;
    }) => ({
      commentId: comment.comment_id,
      authorId: comment.author_id,
      authorName: comment.author_name,
      authorAvatar: comment.author_avatar,
      content: comment.content,
      likeCount: comment.like_count,
      commentTime: comment.create_time,
      replyCount: comment.reply_count,
      replies: comment.replies?.map((reply: {
        comment_id: string;
        author_id: string;
        author_name: string;
        author_avatar: string;
        content: string;
        like_count: number;
        create_time: string;
      }) => ({
        commentId: reply.comment_id,
        authorId: reply.author_id,
        authorName: reply.author_name,
        authorAvatar: reply.author_avatar,
        content: reply.content,
        likeCount: reply.like_count,
        commentTime: reply.create_time,
      })),
    }));
  }

  async getComments(cookies: string, videoId: string): Promise<CommentData[]> {
    // 优先尝试使用 Python API
    const pythonAvailable = await this.checkPythonServiceAvailable();
    if (pythonAvailable) {
      logger.info('[Kuaishou] Python service available, using Python API for comments');
      try {
        return await this.getCommentsViaPython(cookies, videoId);
      } catch (pythonError) {
        logger.warn('[Kuaishou] Python API getComments failed:', pythonError);
      }
    }
    
    // Python API 不可用或失败时返回空
    logger.info(`Kuaishou getComments for video ${videoId} - no implementation`);
    return [];
  }
  
  async replyComment(cookies: string, commentId: string, content: string): Promise<boolean> {
    logger.info(`Kuaishou replyComment ${commentId}: ${content}`);
    return true;
  }
  
  async getAnalytics(cookies: string, dateRange: DateRange): Promise<AnalyticsData> {
    return {
      fansCount: 0,
      fansIncrease: 0,
      viewsCount: 0,
      likesCount: 0,
      commentsCount: 0,
      sharesCount: 0,
    };
  }
}
