import { NextFunction, Request, Response } from 'express';
import { z } from 'zod';
import db from '../../config/database';
import { AutonomousSandboxService } from '../../services/AutonomousSandboxService';
import { DecisionExplainabilityEngine } from '../../core/ai/DecisionExplainabilityEngine';
import { AdviceService } from '../../domains/Strategy/AdviceService';
import { AuditService } from '../../services/AuditService';
import { PixelFeedbackService } from '../../services/PixelFeedbackService';
import { logger } from '../../utils/logger';

export class BizStrategyController {
  /**
   * [FE_SB_01] 运行沙盒模拟 (Run Sandbox Simulation)
   */
  static async runSandboxSimulation(req: Request, res: Response, next: NextFunction) {
    try {
      const { suggestionId, type } = req.body;
      if (!suggestionId || !type) {
        return res.status(400).json({ success: false, error: 'Missing suggestionId or type' });
      }

      const result = await AutonomousSandboxService.runSimulation(suggestionId, type);
      res.json({ success: true, data: result });
    } catch (err) {
      next(err);
    }
  }

  /**
   * [FE_SB_01] 获取沙盒历史运行结果 (Get Sandbox Results)
   */
  static async getSandboxResults(req: Request, res: Response, next: NextFunction) {
    try {
      const { tenantId } = (req as any).traceContext;
      const results = await db('cf_sandbox_runs')
        .where({ tenant_id: tenantId })
        .orderBy('start_time', 'desc')
        .limit(20);

      res.json({ success: true, data: results });
    } catch (err) {
      next(err);
    }
  }

  /**
   * [BIZ_AIS_01] 接收独立站 Pixel 转化事件
   */
  static async collectPixelEvent(req: Request, res: Response, next: NextFunction) {
    try {
      const bodySchema = z.object({
        shopId: z.string(),
        externalProductId: z.string(),
        eventType: z.enum(['VIEW', 'ADD_TO_CART', 'PURCHASE']),
        revenue: z.number().optional(),
        currency: z.string().optional().default('USD')
      });

      const params = bodySchema.parse(req.body);
      const { tenantId, traceId } = (req as any).traceContext;

      await PixelFeedbackService.recordEvent({
        ...params,
        tenantId,
        timestamp: new Date()
      });

      res.json({ success: true, message: 'Event collected' });
    } catch (err: any) {
      if (err instanceof z.ZodError) {
        return res.status(400).json({ success: false, error: err.issues[0].message });
      }
      next(err);
    }
  }

  /**
   * [UX_IAT_01] 切换系统自治紧急停机开关 (Kill-Switch)
   */
  static async toggleKillSwitch(req: Request, res: Response) {
    try {
      const { enabled } = req.body;
      const { tenantId, userId, traceId } = (req as any).traceContext;

      // 实际应存入租户配置表
      logger.warn(`[KillSwitch] Tenant ${tenantId} toggled Kill-Switch to: ${enabled}`);

      await AuditService.log({
        tenantId,
        userId,
        traceId,
        module: 'GOVERNANCE',
        action: 'TOGGLE_KILL_SWITCH',
        resourceType: 'system',
        resourceId: tenantId,
        afterSnapshot: { enabled },
        result: 'success',
        source: 'console'
      });

      res.json({ success: true, data: { killSwitchEnabled: enabled } });
    } catch (err: any) {
      res.status(500).json({ success: false, error: err.message });
    }
  }

  /**
   * [UX_IAT_01] 更新自治模式 (Fully Autonomous / Semi AI)
   */
  static async updateAutonomousMode(req: Request, res: Response) {
    try {
      const { mode } = req.body;
      const { tenantId, userId, traceId } = (req as any).traceContext;

      logger.info(`[Autonomous] Tenant ${tenantId} updated mode to: ${mode}`);

      res.json({ success: true, data: { currentMode: mode } });
    } catch (err: any) {
      res.status(500).json({ success: false, error: err.message });
    }
  }

  /**
   * [UX_IAT_01] 获取系统自治状态
   */
  static async getAutonomousStatus(req: Request, res: Response) {
    try {
      const { tenantId } = (req as any).traceContext;
      // 模拟返回状态
      res.json({ 
        success: true, 
        data: { 
          killSwitchEnabled: false,
          currentMode: 'SEMI_AI',
          activeSimulations: 0
        } 
      });
    } catch (err: any) {
      res.status(500).json({ success: false, error: err.message });
    }
  }

  /**
   * [UX_ADV_01] 获取全站 AGI 策略建议
   */
  static async getAdvice(req: Request, res: Response, next: NextFunction) {
    try {
      const { tenantId, shopId } = (req as any).traceContext;
      const advice = await AdviceService.generateAdvice(tenantId, shopId);
      res.json({ success: true, data: advice });
    } catch (err) {
      next(err);
    }
  }

  /**
   * [UX_ADV_02] 批准并执行 AGI 建议
   */
  static async approveAdvice(req: Request, res: Response, next: NextFunction) {
    try {
      const { adviceId } = req.body;
      const { tenantId, userId, traceId } = (req as any).traceContext;

      await AdviceService.approveAndExecute(adviceId, { tenantId, userId, traceId });
      res.json({ success: true, message: 'Advice approved and execution triggered' });
    } catch (err) {
      next(err);
    }
  }

  /**
   * [UX_XAI_01] 获取 AGI 决策因果叙述 (XAI Narrative)
   */
  static async getAdviceExplanation(req: Request, res: Response, next: NextFunction) {
    try {
      const { adviceId } = req.params;
      const { tenantId } = (req as any).traceContext;
      const explanation = await DecisionExplainabilityEngine.getDecisionNarrative(tenantId, adviceId as string);
      res.json({ success: true, data: explanation });
    } catch (err) {
      next(err);
    }
  }

  /**
   * 编排库存
   */
  static async orchestrateInventory(req: Request, res: Response) {
    try {
      const { tenantId, userId, traceId } = (req as any).traceContext;
      
      logger.info(`[BizStrategyController] Orchestrating inventory for tenant: ${tenantId}`);

      await AuditService.log({
        tenantId,
        userId,
        traceId,
        module: 'STRATEGY',
        action: 'ORCHESTRATE_INVENTORY',
        resourceType: 'INVENTORY',
        resourceId: tenantId,
        afterSnapshot: { status: 'orchestrated' },
        result: 'success',
        source: 'console'
      });

      res.json({ success: true, data: { status: 'orchestrated' } });
    } catch (err: any) {
      res.status(500).json({ success: false, error: err.message });
    }
  }

  /**
   * 批准库存转移
   */
  static async approveTransfer(req: Request, res: Response) {
    try {
      const { transferId } = req.body;
      const { tenantId, userId, traceId } = (req as any).traceContext;

      logger.info(`[BizStrategyController] Approving transfer: ${transferId} for tenant: ${tenantId}`);

      await AuditService.log({
        tenantId,
        userId,
        traceId,
        module: 'STRATEGY',
        action: 'APPROVE_TRANSFER',
        resourceType: 'TRANSFER',
        resourceId: transferId,
        afterSnapshot: { status: 'approved' },
        result: 'success',
        source: 'console'
      });

      res.json({ success: true, data: { transferId, status: 'approved' } });
    } catch (err: any) {
      res.status(500).json({ success: false, error: err.message });
    }
  }

  /**
   * 审查询价
   */
  static async reviewInquiry(req: Request, res: Response) {
    try {
      const { inquiryId } = req.params;
      const { tenantId, userId, traceId } = (req as any).traceContext;

      logger.info(`[BizStrategyController] Reviewing inquiry: ${inquiryId} for tenant: ${tenantId}`);

      await AuditService.log({
        tenantId,
        userId,
        traceId,
        module: 'STRATEGY',
        action: 'REVIEW_INQUIRY',
        resourceType: 'INQUIRY',
        resourceId: inquiryId as string,
        afterSnapshot: { status: 'reviewed' },
        result: 'success',
        source: 'console'
      });

      res.json({ success: true, data: { inquiryId, status: 'reviewed' } });
    } catch (err: any) {
      res.status(500).json({ success: false, error: err.message });
    }
  }

  /**
   * 发送询价
   */
  static async sendInquiry(req: Request, res: Response) {
    try {
      const { inquiryId } = req.params;
      const { tenantId, userId, traceId } = (req as any).traceContext;

      logger.info(`[BizStrategyController] Sending inquiry: ${inquiryId} for tenant: ${tenantId}`);

      await AuditService.log({
        tenantId,
        userId,
        traceId,
        module: 'STRATEGY',
        action: 'SEND_INQUIRY',
        resourceType: 'INQUIRY',
        resourceId: inquiryId as string,
        afterSnapshot: { status: 'sent' },
        result: 'success',
        source: 'console'
      });

      res.json({ success: true, data: { inquiryId, status: 'sent' } });
    } catch (err: any) {
      res.status(500).json({ success: false, error: err.message });
    }
  }

  /**
   * 接受并购买
   */
  static async acceptAndPurchase(req: Request, res: Response) {
    try {
      const { inquiryId } = req.params;
      const { tenantId, userId, traceId } = (req as any).traceContext;

      logger.info(`[BizStrategyController] Accepting and purchasing inquiry: ${inquiryId} for tenant: ${tenantId}`);

      await AuditService.log({
        tenantId,
        userId,
        traceId,
        module: 'STRATEGY',
        action: 'ACCEPT_AND_PURCHASE',
        resourceType: 'INQUIRY',
        resourceId: inquiryId as string,
        afterSnapshot: { status: 'purchased' },
        result: 'success',
        source: 'console'
      });

      res.json({ success: true, data: { inquiryId, status: 'purchased' } });
    } catch (err: any) {
      res.status(500).json({ success: false, error: err.message });
    }
  }

  /**
   * 开始询价
   */
  static async startInquiry(req: Request, res: Response) {
    try {
      const { productId, quantity } = req.body;
      const { tenantId, userId, traceId } = (req as any).traceContext;

      const inquiryId = `inquiry_${tenantId}_${Date.now()}`;

      logger.info(`[BizStrategyController] Starting inquiry for product: ${productId}, quantity: ${quantity} for tenant: ${tenantId}`);

      await AuditService.log({
        tenantId,
        userId,
        traceId,
        module: 'STRATEGY',
        action: 'START_INQUIRY',
        resourceType: 'INQUIRY',
        resourceId: inquiryId,
        afterSnapshot: { productId, quantity, status: 'started' },
        result: 'success',
        source: 'console'
      });

      res.json({ success: true, data: { inquiryId, productId, quantity, status: 'started' } });
    } catch (err: any) {
      res.status(500).json({ success: false, error: err.message });
    }
  }
}
