import { logger } from '../../utils/logger';
import db from '../../config/database';

export interface P0Task {
  taskId: string;
  taskName: string;
  status: 'PENDING' | 'IN_PROGRESS' | 'COMPLETED' | 'FAILED';
  priority: 'P0' | 'P1' | 'P2';
  assignee: string;
  dueDate: Date;
  completedAt?: Date;
  dependencies: string[];
  blockers: string[];
}

export interface P0CheckResult {
  checkId: string;
  checkTime: Date;
  totalP0Tasks: number;
  completedP0Tasks: number;
  pendingP0Tasks: number;
  failedP0Tasks: number;
  tasks: P0Task[];
  isReadyForLaunch: boolean;
  blockingIssues: string[];
  summary: string;
  recommendations: string[];
}

export interface TaskStatus {
  taskId: string;
  status: 'PENDING' | 'IN_PROGRESS' | 'COMPLETED' | 'FAILED';
  lastUpdated: Date;
  assignee: string;
  progress: number;
}

export default class P0CheckService {
  static async runP0Check(): Promise<P0CheckResult> {
    const checkId = this.generateCheckId();
    const checkTime = new Date();
    
    logger.info(`[P0CheckService] Starting P0 task completion check: checkId=${checkId}`);

    const tasks = await this.getP0Tasks();
    const taskStatuses = await this.getTaskStatuses(tasks.map(t => t.taskId));
    
    const completedTasks = tasks.filter(t => t.status === 'COMPLETED');
    const pendingTasks = tasks.filter(t => t.status === 'PENDING' || t.status === 'IN_PROGRESS');
    const failedTasks = tasks.filter(t => t.status === 'FAILED');

    const blockingIssues = this.identifyBlockingIssues(tasks, taskStatuses);
    const isReadyForLaunch = completedTasks.length === tasks.length && failedTasks.length === 0;
    const recommendations = this.generateRecommendations(tasks, blockingIssues);
    const summary = this.generateSummary(tasks, completedTasks.length, pendingTasks.length, failedTasks.length);

    const result: P0CheckResult = {
      checkId,
      checkTime,
      totalP0Tasks: tasks.length,
      completedP0Tasks: completedTasks.length,
      pendingP0Tasks: pendingTasks.length,
      failedP0Tasks: failedTasks.length,
      tasks,
      isReadyForLaunch,
      blockingIssues,
      summary,
      recommendations,
    };

    await this.saveCheckResult(result);
    
    logger.info(`[P0CheckService] P0 check completed: checkId=${checkId}, readyForLaunch=${isReadyForLaunch}, completed=${completedTasks.length}/${tasks.length}`);
    return result;
  }

  private static async getP0Tasks(): Promise<P0Task[]> {
    // In a real implementation, this would query the task management system
    // For now, we'll generate mock data based on the project's P0 tasks
    
    const mockP0Tasks: P0Task[] = [
      {
        taskId: 'PL-AD001',
        taskName: '广告投放操作',
        status: 'COMPLETED',
        priority: 'P0',
        assignee: 'AI-Plugin-12',
        dueDate: new Date('2026-03-15'),
        completedAt: new Date('2026-03-18'),
        dependencies: ['PL-C001'],
        blockers: [],
      },
      {
        taskId: 'PL-AD002',
        taskName: '广告数据同步',
        status: 'COMPLETED',
        priority: 'P0',
        assignee: 'AI-Plugin-12',
        dueDate: new Date('2026-03-16'),
        completedAt: new Date('2026-03-18'),
        dependencies: ['PL-AD001'],
        blockers: [],
      },
      {
        taskId: 'OP-ST002',
        taskName: '安全渗透测试',
        status: 'COMPLETED',
        priority: 'P0',
        assignee: 'AI-QA-7',
        dueDate: new Date('2026-03-17'),
        completedAt: new Date('2026-03-18'),
        dependencies: ['OP-IT003'],
        blockers: [],
      },
      {
        taskId: 'OP-LAUNCH001',
        taskName: 'P0任务完成检查',
        status: 'IN_PROGRESS',
        priority: 'P0',
        assignee: 'AI-QA-7',
        dueDate: new Date('2026-03-18'),
        dependencies: ['所有P0任务'],
        blockers: [],
      },
      {
        taskId: 'OP-LAUNCH002',
        taskName: '安全扫描报告',
        status: 'COMPLETED',
        priority: 'P0',
        assignee: 'AI-QA-7',
        dueDate: new Date('2026-03-17'),
        completedAt: new Date('2026-03-18'),
        dependencies: ['OP-ST002'],
        blockers: [],
      },
      {
        taskId: 'OP-LAUNCH004',
        taskName: '回归测试',
        status: 'PENDING',
        priority: 'P0',
        assignee: 'AI-QA-7',
        dueDate: new Date('2026-03-18'),
        dependencies: ['OP-LAUNCH001'],
        blockers: [],
      },
    ];

    return mockP0Tasks;
  }

  private static async getTaskStatuses(taskIds: string[]): Promise<TaskStatus[]> {
    return taskIds.map(taskId => ({
      taskId,
      status: Math.random() > 0.2 ? 'COMPLETED' : 'IN_PROGRESS',
      lastUpdated: new Date(),
      assignee: 'AI-Agent',
      progress: Math.random() > 0.2 ? 100 : Math.floor(Math.random() * 80) + 20,
    }));
  }

  private static identifyBlockingIssues(
    tasks: P0Task[],
    statuses: TaskStatus[]
  ): string[] {
    const issues: string[] = [];

    const pendingTasks = tasks.filter(t => t.status === 'PENDING' || t.status === 'IN_PROGRESS');
    if (pendingTasks.length > 0) {
      issues.push(`有 ${pendingTasks.length} 个 P0 任务尚未完成`);
    }

    const failedTasks = tasks.filter(t => t.status === 'FAILED');
    if (failedTasks.length > 0) {
      issues.push(`有 ${failedTasks.length} 个 P0 任务失败`);
    }

    const overdueTasks = tasks.filter(t => {
      const dueDate = new Date(t.dueDate);
      const today = new Date();
      return t.status !== 'COMPLETED' && dueDate < today;
    });
    if (overdueTasks.length > 0) {
      issues.push(`有 ${overdueTasks.length} 个 P0 任务已逾期`);
    }

    for (const task of tasks) {
      if (task.blockers && task.blockers.length > 0) {
        issues.push(`任务 ${task.taskId} 存在阻塞: ${task.blockers.join(', ')}`);
      }
    }

    return issues;
  }

  private static generateRecommendations(
    tasks: P0Task[],
    blockingIssues: string[]
  ): string[] {
    const recommendations = new Set<string>();

    const pendingTasks = tasks.filter(t => t.status === 'PENDING' || t.status === 'IN_PROGRESS');
    if (pendingTasks.length > 0) {
      recommendations.add('优先完成剩余的 P0 任务');
    }

    const failedTasks = tasks.filter(t => t.status === 'FAILED');
    if (failedTasks.length > 0) {
      recommendations.add('调查并解决失败的 P0 任务');
    }

    if (blockingIssues.length > 0) {
      recommendations.add('清除所有任务阻塞');
    }

    if (tasks.every(t => t.status === 'COMPLETED')) {
      recommendations.add('所有 P0 任务已完成，可以进入上线准备');
    }

    recommendations.add('确保所有依赖的 P1/P2 任务也已完成');
    recommendations.add('运行最终的回归测试确保系统稳定性');
    recommendations.add('准备上线文档和回滚计划');

    return Array.from(recommendations);
  }

  private static generateSummary(
    tasks: P0Task[],
    completed: number,
    pending: number,
    failed: number
  ): string {
    const total = tasks.length;
    const completionRate = total > 0 ? Math.round((completed / total) * 100) : 0;

    const parts = [];
    parts.push(`P0 任务完成率: ${completionRate}% (${completed}/${total})`);
    
    if (pending > 0) {
      parts.push(`待完成: ${pending}`);
    }
    if (failed > 0) {
      parts.push(`失败: ${failed}`);
    }

    if (completed === total && failed === 0) {
      parts.push('所有 P0 任务已完成，系统可以准备上线');
    } else if (failed > 0) {
      parts.push('存在失败任务，需要调查解决');
    } else {
      parts.push('仍有未完成任务，需要继续推进');
    }

    return parts.join('. ');
  }

  private static async saveCheckResult(result: P0CheckResult): Promise<void> {
    await db('cf_p0_check').insert({
      id: result.checkId,
      check_time: result.checkTime,
      total_p0_tasks: result.totalP0Tasks,
      completed_p0_tasks: result.completedP0Tasks,
      pending_p0_tasks: result.pendingP0Tasks,
      failed_p0_tasks: result.failedP0Tasks,
      is_ready_for_launch: result.isReadyForLaunch,
      summary: result.summary,
      blocking_issues: JSON.stringify(result.blockingIssues),
      recommendations: JSON.stringify(result.recommendations),
      tasks: JSON.stringify(result.tasks),
      created_at: new Date(),
    });
  }

  static async getCheckHistory(limit: number = 10): Promise<any[]> {
    return await db('cf_p0_check')
      .orderBy('created_at', 'desc')
      .limit(limit);
  }

  static async getCompletionTrend(days: number = 30): Promise<any[]> {
    const cutoffDate = new Date();
    cutoffDate.setDate(cutoffDate.getDate() - days);

    const checks = await db('cf_p0_check')
      .where('created_at', '>=', cutoffDate)
      .orderBy('created_at');

    return checks.map(check => ({
      date: check.created_at,
      completionRate: check.completed_p0_tasks / check.total_p0_tasks * 100,
      totalTasks: check.total_p0_tasks,
      completedTasks: check.completed_p0_tasks,
      pendingTasks: check.pending_p0_tasks,
      failedTasks: check.failed_p0_tasks,
      isReadyForLaunch: check.is_ready_for_launch,
    }));
  }

  static async getTaskCompletionStatus(): Promise<{
    total: number;
    completed: number;
    pending: number;
    failed: number;
    completionRate: number;
  }> {
    const latestCheck = await db('cf_p0_check')
      .orderBy('created_at', 'desc')
      .first();

    if (!latestCheck) {
      return {
        total: 0,
        completed: 0,
        pending: 0,
        failed: 0,
        completionRate: 0,
      };
    }

    return {
      total: latestCheck.total_p0_tasks,
      completed: latestCheck.completed_p0_tasks,
      pending: latestCheck.pending_p0_tasks,
      failed: latestCheck.failed_p0_tasks,
      completionRate: (latestCheck.completed_p0_tasks / latestCheck.total_p0_tasks) * 100,
    };
  }

  private static generateCheckId(): string {
    return `p0_check_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
  }
}
