import { NextFunction, Request, Response } from 'express';
import { z } from 'zod';
import { DecisionExplainabilityEngine } from '../../core/ai/DecisionExplainabilityEngine';
import { ShadowAuditService } from '../../core/governance/ShadowAuditService';
import { AutoDiagnosticsService } from '../../core/telemetry/AutoDiagnosticsService';
import { CostAttributionService } from '../../core/telemetry/CostAttributionService';
import { NetworkTopologyService } from '../../core/telemetry/NetworkTopologyService';
import { PredictiveHealthService } from '../../core/telemetry/PredictiveHealthService';
import { SemanticLogService } from '../../core/telemetry/SemanticLogService';
import { AuditService } from '../../services/AuditService';
import { DynamicPricingService } from '../../services/DynamicPricingService';
import { SupplyChainService } from '../../services/SupplyChainService';
import { logger } from '../../utils/logger';

/**
 * [CORE_LOG_03] & [CORE_TELE_AUTO_DIAGNOSTICS] 遥测与系统健康度控制器
 */
export class TelemetryController {
  /**
   * [V31.3] 运行影子测试 (Shadow Audit)
   */
  static async runShadowAudit(req: Request, res: Response, next: NextFunction) {
    try {
      const { tenantId } = req.query;
      if (!tenantId) return res.status(400).json({ success: false, error: 'tenantId is required' });

      const results = await ShadowAuditService.runAllAudits(tenantId as string);
      res.json({ success: true, data: results });
    } catch (err) {
      next(err);
    }
  }
  /**
   * [UX_REVIEW_01] 批量建议批复 (Batch Approve Suggestions)
   */
  static async batchApproveSuggestions(req: Request, res: Response, next: NextFunction) {
    try {
      const { tenantId, pricingIds, sourcingIds } = req.body;
      if (!tenantId) return res.status(400).json({ success: false, error: 'tenantId is required' });

      // [ARCH_PIVOT] 批量安全熔断校验 (TODO: 加入熔断逻辑)
      if ((pricingIds?.length || 0) + (sourcingIds?.length || 0) > 100) {
        return res.status(400).json({ success: false, error: 'Batch size too large. Max 100 per request.' });
      }

      const results = {
        pricing: 0,
        sourcing: 0
      };

      if (pricingIds?.length > 0) {
        // 批量执行定价决策
        let approvedCount = 0;
        for (const decisionId of pricingIds) {
          try {
            await DynamicPricingService.executePricingDecision(tenantId, decisionId);
            approvedCount++;
          } catch (err) {
            logger.error(`[TelemetryController] Failed to approve pricing decision ${decisionId}:`, err);
          }
        }
        results.pricing = approvedCount;
      }

      if (sourcingIds?.length > 0) {
        results.sourcing = await SupplyChainService.approveSuggestions(tenantId, sourcingIds);
      }

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

  /**
   * [BIZ_GOV_05] 获取建议采纳 ROI 实时看板
   */
  static async getRoiDashboard(req: Request, res: Response, next: NextFunction) {
    try {
      const { tenantId } = req.query;
      if (!tenantId) return res.status(400).json({ success: false, error: 'tenantId is required' });

      const stats = await DecisionExplainabilityEngine.getRoiStats(tenantId as string);
      res.json({ success: true, data: stats });
    } catch (err) {
      next(err);
    }
  }
  /**
   * 运行系统诊断 (CORE_TELE_10)
   */
  static async runDiagnostics(req: Request, res: Response, next: NextFunction) {
    try {
      const { tenantId } = req.query;
      if (!tenantId) return res.status(400).json({ success: false, error: 'tenantId is required' });
      const result = await AutoDiagnosticsService.runDiagnostics(tenantId as string);
      res.json({ success: true, data: result });
    } catch (err) {
      next(err);
    }
  }

  /**
   * 获取健康预测 (CORE_TELE_PREDICTIVE_HEALTH)
   */
  static async getHealthPrediction(req: Request, res: Response, next: NextFunction) {
    try {
      const { tenantId } = req.query;
      if (!tenantId) return res.status(400).json({ success: false, error: 'tenantId is required' });
      const prediction = await PredictiveHealthService.predictHealth(tenantId as string);
      res.json({ success: true, data: prediction });
    } catch (err) {
      next(err);
    }
  }

  /**
   * [CORE_TELE_TOPO] 获取全球节点实时拓扑遥测 (Network Topology)
   */
  static async getNetworkTopology(req: Request, res: Response, next: NextFunction) {
    try {
      const { tenantId } = (req as any).traceContext || req.query;
      if (!tenantId) return res.status(400).json({ success: false, error: 'tenantId is required' });
      
      const topology = await NetworkTopologyService.getTopologySnapshot();
      res.json({ success: true, data: topology });
    } catch (err) {
      next(err);
    }
  }

  /**
   * 获取租户 API 账单 (CORE_TELE_08)
   */
  static async getApiBill(req: Request, res: Response, next: NextFunction) {
    try {
      const { tenantId } = req.params;
      const bill = await CostAttributionService.getTenantBill(tenantId as string);
      res.json({ success: true, data: bill });
    } catch (err) {
      next(err);
    }
  }

  /**
   * 语义搜索日志
   */
  static async searchSemanticLogs(req: Request, res: Response, next: NextFunction) {
    try {
      const { query, limit } = req.query;
      const results = await SemanticLogService.searchLogs(query as string, Number(limit) || 20);
      res.json({ success: true, data: results });
    } catch (err) {
      next(err);
    }
  }

  /**
   * [UX_EXT_19] 插件端上报异常 (Anomaly Reporting)
   */
  static async reportAnomaly(req: Request, res: Response, next: NextFunction) {
    try {
      const bodySchema = z.object({
        module: z.string(),
        anomalyType: z.string(),
        reason: z.string(),
        metadata: z.any().optional()
      });

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

      logger.warn(`[Anomaly] ${params.module} reported anomaly: ${params.anomalyType} - ${params.reason}`);

      // 1. 记录语义日志
      await SemanticLogService.logSemantic(
        `[EXT_REPORT] ${params.anomalyType}: ${params.reason}`,
        'WARN',
        params.module
      );

      // 2. 存入审计表
      await AuditService.log({
        tenantId,
        userId,
        traceId,
        module: 'TELEMETRY',
        action: 'REPORT_ANOMALY',
        resourceType: 'extension',
        resourceId: params.module,
        afterSnapshot: params,
        result: 'success',
        source: 'extension'
      });

      res.json({ success: true, message: 'Anomaly reported and logged' });
    } catch (err) {
      next(err);
    }
  }

  /**
   * 集群异常模式
   */
  static async clusterAnomalyPatterns(req: Request, res: Response, next: NextFunction) {
    try {
      const { tenantId } = (req as any).traceContext;
      
      logger.info(`[TelemetryController] Clustering anomaly patterns for tenant: ${tenantId}`);

      const patterns = await SemanticLogService.searchLogs('anomaly', 50);

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