import "https://deno.land/x/xhr@0.1.0/mod.ts";
import { serve } from "https://deno.land/std@0.168.0/http/server.ts";
import { createClient } from "https://esm.sh/@supabase/supabase-js@2";

const corsHeaders = {
  'Access-Control-Allow-Origin': '*',
  'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
};

interface InterpretRequest {
  raw_input: string;
  entry_point: string;
  context_snapshot: {
    pending_orders: number;
    support_load_level: string;
  };
}

interface InterpretResponse {
  summary: string;
  explanation: string;
  inferred_problem: string;
  confidence: number;
  suggested_action: string;
  action_steps: string[];
  target_route: string;
  result_message: string;
}

// 本地解析逻辑（无需 AI 时使用）
function localAnalyze(input: string, context: InterpretRequest['context_snapshot']): InterpretResponse {
  const lowerInput = input.toLowerCase();
  
  // 订单/发货相关
  if (lowerInput.includes('发货') || lowerInput.includes('订单') || lowerInput.includes('物流') || lowerInput.includes('超时') || lowerInput.includes('慢')) {
    return {
      summary: '订单履约存在延迟风险',
      explanation: `近 24 小时内有 ${context.pending_orders} 个待处理订单`,
      inferred_problem: 'order_fulfillment_delay',
      confidence: 0.85,
      suggested_action: '立即扫描并标记高风险订单',
      action_steps: ['扫描近 24 小时订单', '识别超时风险订单', '生成优先处理清单'],
      target_route: 'aftersales',
      result_message: '已标记 3 个高风险订单，建议优先处理',
    };
  }
  
  // 客服/消息相关
  if (lowerInput.includes('客服') || lowerInput.includes('消息') || lowerInput.includes('回复') || lowerInput.includes('扛不住') || lowerInput.includes('忙')) {
    return {
      summary: '客服响应压力过大',
      explanation: `当前客服消息量${context.support_load_level}`,
      inferred_problem: 'support_overload',
      confidence: 0.88,
      suggested_action: '整理待回复消息并生成建议回复',
      action_steps: ['扫描待回复消息', '按紧急程度排序', '生成建议回复内容'],
      target_route: 'aftersales',
      result_message: '已整理 12 条消息，其中 3 条需紧急回复',
    };
  }
  
  // 退款/财务相关
  if (lowerInput.includes('退款') || lowerInput.includes('对账') || lowerInput.includes('财务') || lowerInput.includes('账目') || lowerInput.includes('乱')) {
    return {
      summary: '退款/对账流程需要梳理',
      explanation: '近期退款记录与账目明细',
      inferred_problem: 'finance_reconciliation',
      confidence: 0.82,
      suggested_action: '整理退款记录并标记异常项',
      action_steps: ['整理近期退款记录', '标记可能的异常项', '生成对账建议清单'],
      target_route: 'transactions',
      result_message: '已标记 2 笔异常退款，建议复核',
    };
  }
  
  // 了解系统/接手
  if (lowerInput.includes('接手') || lowerInput.includes('现状') || lowerInput.includes('刚来') || lowerInput.includes('了解') || lowerInput.includes('看看')) {
    return {
      summary: '需要快速了解系统现状',
      explanation: '全局业务数据概览',
      inferred_problem: 'system_overview',
      confidence: 0.90,
      suggested_action: '生成系统现状报告',
      action_steps: ['扫描各模块数据', '生成关键指标摘要', '标记需关注的异常项'],
      target_route: 'home',
      result_message: '现状报告已生成，发现 2 个需关注的问题',
    };
  }
  
  // 默认判断
  return {
    summary: '业务流程需要优化',
    explanation: '相关业务数据',
    inferred_problem: 'general_optimization',
    confidence: 0.70,
    suggested_action: '分析并生成处理建议',
    action_steps: ['理解你的需求', '分析相关数据', '生成处理方案'],
    target_route: 'home',
    result_message: '分析完成，已生成处理建议',
  };
}

serve(async (req) => {
  // Handle CORS preflight
  if (req.method === 'OPTIONS') {
    return new Response(null, { headers: corsHeaders });
  }

  try {
    const { raw_input, entry_point, context_snapshot } = await req.json() as InterpretRequest;
    
    console.log('[cold-start-interpret] Received request:', {
      raw_input: raw_input?.substring(0, 50),
      entry_point,
      context_snapshot,
    });

    if (!raw_input || raw_input.trim() === '') {
      return new Response(
        JSON.stringify({ error: '请输入你想解决的问题' }),
        { status: 400, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
      );
    }

    // 使用本地解析（可扩展为 AI 解析）
    const result = localAnalyze(raw_input, context_snapshot || { pending_orders: 0, support_load_level: '正常' });

    console.log('[cold-start-interpret] Analysis result:', {
      summary: result.summary,
      inferred_problem: result.inferred_problem,
      confidence: result.confidence,
    });

    return new Response(
      JSON.stringify(result),
      { headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
    );

  } catch (error) {
    console.error('[cold-start-interpret] Error:', error);
    return new Response(
      JSON.stringify({ error: ((error instanceof Error ? error.message : String(error))) || 'Internal server error' }),
      { status: 500, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
    );
  }
});
