import { logger } from '../utils/logger';
import { FeatureGovernanceService } from '../core/governance/FeatureGovernanceService';
import { AIService } from './AIService';

interface DecisionInput {
  tenantId: string;
  shopId?: string;
  taskId?: string;
  traceId: string;
  businessType: 'TOC' | 'TOB';
  decisionType: 'PRICING' | 'PROMOTION' | 'INVENTORY' | 'LOGISTICS' | 'SUPPLIER';
  context: Record<string, any>;
  options: Array<{
    id: string;
    name: string;
    impact: Record<string, number>;
    cost?: number;
  }>;
}

interface DecisionOutput {
  recommendedOption: string;
  confidence: number;
  reasoning: string;
  riskScore: number;
  expectedImpact: Record<string, number>;
  executionPath: 'AUTO' | 'REVIEW' | 'MANUAL';
}

export class AIDecisionSystem {
  /**
   * 执行AI决策
   */
  static async makeDecision(input: DecisionInput): Promise<DecisionOutput> {
    logger.info(`[AIDecisionSystem] Making decision - type: ${input.decisionType}, tenantId: ${input.tenantId}`);

    try {
      // 检查功能开关
      if (!(await FeatureGovernanceService.isEnabled('AI_DECISION_SYSTEM', input.tenantId))) {
        return this.getDefaultDecision(input);
      }

      // 根据决策类型执行不同的决策逻辑
      switch (input.decisionType) {
        case 'PRICING':
          return this.makePricingDecision(input);
        case 'PROMOTION':
          return this.makePromotionDecision(input);
        case 'INVENTORY':
          return this.makeInventoryDecision(input);
        case 'LOGISTICS':
          return this.makeLogisticsDecision(input);
        case 'SUPPLIER':
          return this.makeSupplierDecision(input);
        default:
          return this.getDefaultDecision(input);
      }
    } catch (error: any) {
      logger.error(`[AIDecisionSystem] Decision failed: ${error.message}`);
      return this.getDefaultDecision(input);
    }
  }

  /**
   * 定价决策
   */
  private static async makePricingDecision(input: DecisionInput): Promise<DecisionOutput> {
    const { options, context } = input;

    // 计算每个选项的综合评分
    const scoredOptions = options.map(option => {
      let score = 0;
      
      // 考虑利润影响
      if (option.impact.profit) {
        score += option.impact.profit * 0.4;
      }
      
      // 考虑竞争力影响
      if (option.impact.competitiveness) {
        score += option.impact.competitiveness * 0.3;
      }
      
      // 考虑销量影响
      if (option.impact.sales) {
        score += option.impact.sales * 0.2;
      }
      
      // 考虑成本
      if (option.cost) {
        score -= option.cost * 0.1;
      }
      
      return { ...option, score };
    });

    // 选择评分最高的选项
    scoredOptions.sort((a, b) => b.score - a.score);
    const bestOption = scoredOptions[0];

    // 计算置信度
    const confidence = Math.min(0.95, bestOption.score / (scoredOptions.reduce((sum, opt) => sum + opt.score, 0) || 1));

    // 计算风险分数
    const riskScore = this.calculateRiskScore(bestOption, context);

    // 决定执行路径
    let executionPath: 'AUTO' | 'REVIEW' | 'MANUAL' = 'AUTO';
    if (riskScore > 0.7) {
      executionPath = 'MANUAL';
    } else if (riskScore > 0.4) {
      executionPath = 'REVIEW';
    }

    return {
      recommendedOption: bestOption.id,
      confidence,
      reasoning: `Selected ${bestOption.name} based on profit impact (40%), competitiveness (30%), sales impact (20%), and cost (10%).`,
      riskScore,
      expectedImpact: bestOption.impact,
      executionPath
    };
  }

  /**
   * 促销决策
   */
  private static async makePromotionDecision(input: DecisionInput): Promise<DecisionOutput> {
    const { options, context } = input;

    // 计算每个选项的综合评分
    const scoredOptions = options.map(option => {
      let score = 0;
      
      // 考虑促销效果
      if (option.impact.promotionEffect) {
        score += option.impact.promotionEffect * 0.4;
      }
      
      // 考虑客户获取
      if (option.impact.customerAcquisition) {
        score += option.impact.customerAcquisition * 0.3;
      }
      
      // 考虑品牌影响力
      if (option.impact.brandImpact) {
        score += option.impact.brandImpact * 0.2;
      }
      
      // 考虑成本
      if (option.cost) {
        score -= option.cost * 0.1;
      }
      
      return { ...option, score };
    });

    // 选择评分最高的选项
    scoredOptions.sort((a, b) => b.score - a.score);
    const bestOption = scoredOptions[0];

    // 计算置信度
    const confidence = Math.min(0.95, bestOption.score / (scoredOptions.reduce((sum, opt) => sum + opt.score, 0) || 1));

    // 计算风险分数
    const riskScore = this.calculateRiskScore(bestOption, context);

    // 决定执行路径
    let executionPath: 'AUTO' | 'REVIEW' | 'MANUAL' = 'AUTO';
    if (riskScore > 0.7) {
      executionPath = 'MANUAL';
    } else if (riskScore > 0.4) {
      executionPath = 'REVIEW';
    }

    return {
      recommendedOption: bestOption.id,
      confidence,
      reasoning: `Selected ${bestOption.name} based on promotion effect (40%), customer acquisition (30%), brand impact (20%), and cost (10%).`,
      riskScore,
      expectedImpact: bestOption.impact,
      executionPath
    };
  }

  /**
   * 库存决策
   */
  private static async makeInventoryDecision(input: DecisionInput): Promise<DecisionOutput> {
    const { options, context } = input;

    // 计算每个选项的综合评分
    const scoredOptions = options.map(option => {
      let score = 0;
      
      // 考虑库存周转率
      if (option.impact.turnover) {
        score += option.impact.turnover * 0.3;
      }
      
      // 考虑缺货风险
      if (option.impact.stockoutRisk) {
        score += (1 - option.impact.stockoutRisk) * 0.3;
      }
      
      // 考虑存储成本
      if (option.impact.storageCost) {
        score += (1 - option.impact.storageCost) * 0.2;
      }
      
      // 考虑资金占用
      if (option.impact.capitalOccupancy) {
        score += (1 - option.impact.capitalOccupancy) * 0.2;
      }
      
      return { ...option, score };
    });

    // 选择评分最高的选项
    scoredOptions.sort((a, b) => b.score - a.score);
    const bestOption = scoredOptions[0];

    // 计算置信度
    const confidence = Math.min(0.95, bestOption.score / (scoredOptions.reduce((sum, opt) => sum + opt.score, 0) || 1));

    // 计算风险分数
    const riskScore = this.calculateRiskScore(bestOption, context);

    // 决定执行路径
    let executionPath: 'AUTO' | 'REVIEW' | 'MANUAL' = 'AUTO';
    if (riskScore > 0.7) {
      executionPath = 'MANUAL';
    } else if (riskScore > 0.4) {
      executionPath = 'REVIEW';
    }

    return {
      recommendedOption: bestOption.id,
      confidence,
      reasoning: `Selected ${bestOption.name} based on turnover (30%), stockout risk (30%), storage cost (20%), and capital occupancy (20%).`,
      riskScore,
      expectedImpact: bestOption.impact,
      executionPath
    };
  }

  /**
   * 物流决策
   */
  private static async makeLogisticsDecision(input: DecisionInput): Promise<DecisionOutput> {
    const { options, context } = input;

    // 计算每个选项的综合评分
    const scoredOptions = options.map(option => {
      let score = 0;
      
      // 考虑物流速度
      if (option.impact.speed) {
        score += option.impact.speed * 0.3;
      }
      
      // 考虑物流成本
      if (option.impact.cost) {
        score += (1 - option.impact.cost) * 0.3;
      }
      
      // 考虑可靠性
      if (option.impact.reliability) {
        score += option.impact.reliability * 0.2;
      }
      
      // 考虑可追踪性
      if (option.impact.trackability) {
        score += option.impact.trackability * 0.2;
      }
      
      return { ...option, score };
    });

    // 选择评分最高的选项
    scoredOptions.sort((a, b) => b.score - a.score);
    const bestOption = scoredOptions[0];

    // 计算置信度
    const confidence = Math.min(0.95, bestOption.score / (scoredOptions.reduce((sum, opt) => sum + opt.score, 0) || 1));

    // 计算风险分数
    const riskScore = this.calculateRiskScore(bestOption, context);

    // 决定执行路径
    let executionPath: 'AUTO' | 'REVIEW' | 'MANUAL' = 'AUTO';
    if (riskScore > 0.7) {
      executionPath = 'MANUAL';
    } else if (riskScore > 0.4) {
      executionPath = 'REVIEW';
    }

    return {
      recommendedOption: bestOption.id,
      confidence,
      reasoning: `Selected ${bestOption.name} based on speed (30%), cost (30%), reliability (20%), and trackability (20%).`,
      riskScore,
      expectedImpact: bestOption.impact,
      executionPath
    };
  }

  /**
   * 供应商决策
   */
  private static async makeSupplierDecision(input: DecisionInput): Promise<DecisionOutput> {
    const { options, context } = input;

    // 计算每个选项的综合评分
    const scoredOptions = options.map(option => {
      let score = 0;
      
      // 考虑价格
      if (option.impact.price) {
        score += (1 - option.impact.price) * 0.3;
      }
      
      // 考虑质量
      if (option.impact.quality) {
        score += option.impact.quality * 0.3;
      }
      
      // 考虑交付可靠性
      if (option.impact.deliveryReliability) {
        score += option.impact.deliveryReliability * 0.2;
      }
      
      // 考虑服务水平
      if (option.impact.serviceLevel) {
        score += option.impact.serviceLevel * 0.2;
      }
      
      return { ...option, score };
    });

    // 选择评分最高的选项
    scoredOptions.sort((a, b) => b.score - a.score);
    const bestOption = scoredOptions[0];

    // 计算置信度
    const confidence = Math.min(0.95, bestOption.score / (scoredOptions.reduce((sum, opt) => sum + opt.score, 0) || 1));

    // 计算风险分数
    const riskScore = this.calculateRiskScore(bestOption, context);

    // 决定执行路径
    let executionPath: 'AUTO' | 'REVIEW' | 'MANUAL' = 'AUTO';
    if (riskScore > 0.7) {
      executionPath = 'MANUAL';
    } else if (riskScore > 0.4) {
      executionPath = 'REVIEW';
    }

    return {
      recommendedOption: bestOption.id,
      confidence,
      reasoning: `Selected ${bestOption.name} based on price (30%), quality (30%), delivery reliability (20%), and service level (20%).`,
      riskScore,
      expectedImpact: bestOption.impact,
      executionPath
    };
  }

  /**
   * 计算风险分数
   */
  private static calculateRiskScore(option: any, context: Record<string, any>): number {
    let riskScore = 0;

    // 检查成本风险
    if (option.cost && option.cost > (context.budget || 1000)) {
      riskScore += 0.3;
    }

    // 检查影响风险
    if (option.impact.risk) {
      riskScore += option.impact.risk * 0.4;
    }

    // 检查市场风险
    if (context.marketVolatility && context.marketVolatility > 0.5) {
      riskScore += 0.2;
    }

    // 检查时间风险
    if (context.timeSensitivity && context.timeSensitivity > 0.7) {
      riskScore += 0.1;
    }

    return Math.min(1, riskScore);
  }

  /**
   * 获取默认决策
   */
  private static getDefaultDecision(input: DecisionInput): DecisionOutput {
    // 简单选择第一个选项
    const defaultOption = input.options[0];

    return {
      recommendedOption: defaultOption.id,
      confidence: 0.5,
      reasoning: 'Using default decision due to feature disabled or error',
      riskScore: 0.5,
      expectedImpact: defaultOption.impact,
      executionPath: 'MANUAL'
    };
  }

  /**
   * 执行决策后评估
   */
  static async evaluateDecision(decisionId: string, actualOutcome: Record<string, any>): Promise<{
    accuracy: number;
    improvement: number;
    lessons: string[];
  }> {
    logger.info(`[AIDecisionSystem] Evaluating decision: ${decisionId}`);

    try {
      // 这里可以实现决策后评估逻辑
      // 比如比较预期结果和实际结果的差异
      
      return {
        accuracy: 0.85,
        improvement: 0.15,
        lessons: [
          'Consider market volatility in pricing decisions',
          'Improve cost estimation accuracy',
          'Enhance risk assessment for high-value decisions'
        ]
      };
    } catch (error: any) {
      logger.error(`[AIDecisionSystem] Evaluation failed: ${error.message}`);
      return {
        accuracy: 0.5,
        improvement: 0,
        lessons: []
      };
    }
  }
}
