import db from '../config/database';
import { AIService } from './AIService';
import { AuditService } from './AuditService';

/**
 * [BIZ_MKT_09] 社交媒体负面舆情监控与公关建议
 * 负责扫描各大社交平台（TikTok/IG/FB）关于品牌的负面言论，并自动生成公关建议
 */
export class PRMonitorService {
  /**
   * 记录发现的舆情并生成建议
   */
  static async logAndAnalyzePR(
    tenantId: string,
    platform: string,
    keyword: string,
    content: string,
    traceId: string
  ): Promise<number> {
    // 1. 情感分析 (模拟调用 AIService)
    const analysis = await AIService.analyzeSentiment(content);
    const sentiment = analysis.score; // -1 to 1

    // 2. 风险等级判定
    let riskLevel: 'LOW' | 'MEDIUM' | 'HIGH' | 'CRITICAL' = 'LOW';
    if (sentiment < -0.8) riskLevel = 'CRITICAL';
    else if (sentiment < -0.5) riskLevel = 'HIGH';
    else if (sentiment < -0.2) riskLevel = 'MEDIUM';

    // 3. 生成公关建议 (AI 自动生成响应策略)
    const aiSuggestion = await this.generatePRSuggestion(content, riskLevel);

    // 4. 持久化记录
    const [id] = await db('cf_pr_monitor').insert({
      tenant_id: tenantId,
      platform,
      keyword,
      content,
      sentiment_score: sentiment,
      risk_level: riskLevel,
      ai_suggestion: aiSuggestion,
      status: 'UNHANDLED'
    });

    // 5. 高风险舆情报警记录
    if (riskLevel === 'HIGH' || riskLevel === 'CRITICAL') {
      await AuditService.log({
        tenant_id: tenantId,
        action: 'PR_CRITICAL_ALERT',
        target_type: 'PR_MONITOR',
        target_id: id.toString(),
        trace_id: traceId,
        new_data: JSON.stringify({ riskLevel, sentiment }),
        metadata: JSON.stringify({ content: content.slice(0, 50) + '...' })
      });
    }

    return id;
  }

  /**
   * 生成公关建议话术
   */
  private static async generatePRSuggestion(content: string, riskLevel: string): Promise<string> {
    if (riskLevel === 'CRITICAL') {
      return "URGENT: Issue official apology within 4 hours. Reach out to the user via private message immediately to resolve the issue.";
    } else if (riskLevel === 'HIGH') {
      return "High Priority: Prepare a supportive comment addressing the user's concern. Monitor the thread for escalation.";
    } else if (riskLevel === 'MEDIUM') {
      return "Standard Priority: Standard customer service response needed. Clarify misunderstandings if any.";
    }
    return "Low Priority: Observe only. No immediate action required.";
  }

  /**
   * 获取租户所有未处理的高风险舆情
   */
  static async getCriticalIssues(tenantId: string) {
    return await db('cf_pr_monitor')
      .where({ tenant_id: tenantId, status: 'UNHANDLED' })
      .whereIn('risk_level', ['HIGH', 'CRITICAL'])
      .orderBy('created_at', 'desc');
  }
}
