/**
 * coze-chat Edge Function
 * C端消费者聊天 - Coze Agent 接入
 * 
 * 功能：
 * 1. 接收用户消息，调用 Coze API
 * 2. 动态获取 Agent 规范（通过 consumer-agent-spec）
 * 3. 支持产品目录注入
 * 4. 支持对话历史维护
 * 5. 备用 Lovable AI Gateway 降级
 */

import { createClient } from 'https://esm.sh/@supabase/supabase-js@2.57.4';

// === AI Hub routing (auto-injected) ===
const _HUB_KEY = Deno.env.get("AI_HUB_API_KEY") || "";
const _HUB_BASE = (Deno.env.get("AI_HUB_BASE_URL") || "").replace(/\/+$/, "");
const _USE_HUB = !!(_HUB_KEY && _HUB_BASE);
const _AI_CHAT_URL = _USE_HUB ? `${_HUB_BASE}/chat/completions` : "https://ai.gateway.lovable.dev/v1/chat/completions";
const _AI_CHAT_KEY = _USE_HUB ? _HUB_KEY : (Deno.env.get("LOVABLE_API_KEY") || "");
const _AI_CHAT_DEFAULT_MODEL = Deno.env.get('AI_HUB_DEFAULT_CHAT_MODEL') || 'agent-default';
const _mapAiModel = (m: string) => (_USE_HUB && /^(google|openai|anthropic)\//i.test(m || '')) ? _AI_CHAT_DEFAULT_MODEL : m;
// === end AI Hub routing ===


const corsHeaders = {
  'Access-Control-Allow-Origin': '*',
  'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type, x-trace-id, x-user-id',
  'Access-Control-Allow-Methods': 'POST, OPTIONS',
};

interface CozeRequest {
  message: string;
  conversationId?: string;
  inputs: {
    user_id?: string;
    trace_id: string;
    user_context?: string;
    product?: {
      id: string;
      title: string;
      description?: string;
      price?: number;
    };
    catalog?: Array<{
      id: string;
      name: string;
      price: number;
      stock_quantity?: number;
      category?: string;
      description?: string;
    }>;
  };
}

interface CozeResponse {
  title: string;
  intent: "SHOPPING" | "AFTERSALES" | "GENERAL" | "COMPARE";
  sentiment: "POSITIVE" | "NEUTRAL" | "NEGATIVE";
  highlights: string[];
  picks: Array<{
    product_id: string;
    note: string;
    source?: string;
  }>;
  comparison?: string;
  next: string[];
  meta: {
    platform: string;
    user: string;
    catalog_count: number;
    probe_id: string;
  };
  answer?: string;
  conversation_id?: string;
}

// ========================
// Agent 规范缓存
// ========================
let cachedAgentSpec: any = null;
let cacheTimestamp = 0;
const CACHE_TTL_MS = 5 * 60 * 1000; // 5分钟缓存

async function fetchAgentSpec(): Promise<any> {
  const now = Date.now();
  
  if (cachedAgentSpec && (now - cacheTimestamp) < CACHE_TTL_MS) {
    console.log('📦 Using cached agent spec');
    return cachedAgentSpec;
  }
  
  try {
    const supabaseUrl = Deno.env.get('SUPABASE_URL')!;
    const specUrl = `${supabaseUrl}/functions/v1/consumer-agent-spec?format=full`;
    
    console.log('🔄 Fetching agent spec from:', specUrl);
    
    const response = await fetch(specUrl, {
      method: 'GET',
      headers: { 'Content-Type': 'application/json' }
    });
    
    if (!response.ok) {
      throw new Error(`Failed to fetch agent spec: ${response.status}`);
    }
    
    const spec = await response.json();
    cachedAgentSpec = spec;
    cacheTimestamp = now;
    
    console.log('✅ Agent spec loaded:', { 
      persona: spec.persona?.name,
      intentsCount: spec.intents?.length || 0 
    });
    
    return spec;
  } catch (error) {
    console.error('❌ Failed to fetch agent spec:', error);
    return getDefaultAgentSpec();
  }
}

function getDefaultAgentSpec(): any {
  return {
    persona: {
      name: "小智",
      role: "智能购物顾问",
      tone: "friendly"
    },
    system_prompt: `你是一个专业的手机销售顾问助手。

## 输出格式规范（重要！）

### 推荐产品时必须使用此格式：
1. 产品名称 - ¥价格
   推荐理由：一句话说明

2. 产品名称 - ¥价格
   推荐理由：一句话说明

前端会自动解析 "产品名 - ¥价格" 格式生成产品卡片。

### 对比产品时使用Markdown表格：
| 对比项 | 产品A | 产品B |
|--------|-------|-------|
| 价格 | ¥xxx | ¥xxx |`,
    intents: [],
    io_protocol: null
  };
}

// 构建系统提示词
function buildSystemPrompt(
  agentSpec: any,
  userInfo: any,
  catalog: any[],
  userContext?: string
): string {
  const persona = agentSpec.persona || {};
  const basePrompt = agentSpec.system_prompt || '';
  const ioProtocol = agentSpec.io_protocol;
  
  let systemPrompt = `# ${persona.name || '小智'} - ${persona.role || '智能购物顾问'}

${basePrompt}

## 用户信息
- 用户ID: ${userInfo.id}
- 邮箱: ${userInfo.email || 'unknown'}

## ⚠️⚠️⚠️ 最重要的规则 - 产品推荐格式 ⚠️⚠️⚠️

当推荐产品时，你**必须且只能**使用下面产品目录中的真实 product_id！

**可用产品目录（共${catalog.length}个，请从这里选择）：**
${catalog.slice(0, 30).map(p => `• ID="${p.id}" | ${p.name} | ¥${p.price}`).join('\n')}
${catalog.length > 30 ? `\n...还有${catalog.length - 30}个产品` : ''}

**输出格式（必须在回复末尾包含）：**
\`\`\`json
{
  "picks": [
    {"product_id": "从上面目录复制的真实ID", "note": "推荐理由"}
  ]
}
\`\`\`

**⚠️ 严格规则：**
1. product_id **必须**从上面产品目录中复制，不要编造！
2. 如果目录中没有匹配的产品，返回空 picks: []
3. 例如用户问"小米手机"，你应该找到目录中包含"小米"的产品，复制其完整 ID
4. 错误示例：\`"product_id": "e5f6a7b8-xxxx"\` ❌（这是编造的）
5. 正确示例：\`"product_id": "242a6f6e-3afd-4c0d-b8a2-aaaeee077157"\` ✅（从目录复制）
`;

  // 添加 Mem0 记忆上下文
  if (userContext) {
    systemPrompt += `\n## 用户历史偏好（来自记忆系统）\n${userContext}\n`;
  }

  // 添加意图规则
  if (agentSpec.intents && agentSpec.intents.length > 0) {
    systemPrompt += `\n## 意图识别规则\n`;
    agentSpec.intents.forEach((intent: any) => {
      systemPrompt += `- ${intent.id}: ${intent.description} → ${intent.action}\n`;
    });
  }

  // 添加输出格式协议
  if (ioProtocol?.output_format) {
    const outputFormat = ioProtocol.output_format;
    systemPrompt += `\n## 额外输出格式参考
${outputFormat.product_recommendation?.description || ''}
`;
  }

  return systemPrompt;
}

// 解析文本响应 - 优先提取JSON格式的picks
function parseTextResponse(text: string, catalog: any[], userMessage: string): {
  intent: "SHOPPING" | "AFTERSALES" | "GENERAL" | "COMPARE";
  picks: Array<{ product_id: string; note: string; source?: string; }>;
  highlights: string[];
} {
  const result = {
    intent: "GENERAL" as "SHOPPING" | "AFTERSALES" | "GENERAL" | "COMPARE",
    picks: [] as Array<{ product_id: string; note: string; source?: string; }>,
    highlights: [] as string[],
  };

  // 意图检测
  const shoppingKeywords = ['买', '购', '推荐', '价格', '多少钱', '便宜', '贵', '选择', '哪个好', '手机', '电脑'];
  const afterSalesKeywords = ['退货', '换货', '售后', '维修', '保修', '质量问题', '投诉'];
  const compareKeywords = ['对比', '比较', '哪个更好', '区别', 'vs', 'VS'];
  
  if (compareKeywords.some(kw => userMessage.includes(kw))) {
    result.intent = "COMPARE";
  } else if (shoppingKeywords.some(kw => userMessage.includes(kw)) || text.includes('推荐') || text.includes('picks')) {
    result.intent = "SHOPPING";
  } else if (afterSalesKeywords.some(kw => userMessage.includes(kw))) {
    result.intent = "AFTERSALES";
  }

  // ✅ 优先：尝试从回复中提取 JSON 格式的 picks
  // 保存原始 JSON picks 用于降级
  let originalJsonPicks: Array<{ product_id: string; note: string }> = [];
  
  try {
    // 匹配 JSON 代码块
    const jsonMatch = text.match(/```json\s*([\s\S]*?)\s*```/);
    if (jsonMatch) {
      const jsonStr = jsonMatch[1];
      const parsed = JSON.parse(jsonStr);
      if (parsed.picks && Array.isArray(parsed.picks)) {
        console.log('✅ 从 JSON 块提取到 picks:', parsed.picks.length);
        
        // 保存原始数据用于降级
        originalJsonPicks = parsed.picks.map((p: any) => ({
          product_id: p.product_id,
          note: p.note || ''
        }));
        
        result.picks = parsed.picks.map((p: any) => ({
          product_id: p.product_id,
          note: p.note || '',
          source: 'coze-json'
        }));
        
        // 验证产品ID是否存在于目录中
        result.picks = result.picks.filter(pick => {
          const exists = catalog.some(c => c.id === pick.product_id);
          if (!exists) {
            console.warn('⚠️ 产品ID不在目录中:', pick.product_id);
          }
          return exists;
        });
        
        // ✅ 去重：确保每个 product_id 只出现一次
        const seenIds = new Set<string>();
        result.picks = result.picks.filter(pick => {
          if (seenIds.has(pick.product_id)) {
            console.warn('⚠️ 跳过重复产品ID:', pick.product_id);
            return false;
          }
          seenIds.add(pick.product_id);
          return true;
        });
        
        // ❌ 移除"产品名降级匹配"——这是幻觉放大器
        // 当 Coze 返回幻觉 ID 时，用 AI 文本中出现的名词去匹配真实目录会造成
        // "答非所问"的错误推荐（用户问"干燥箱" → AI 文案写了"iQOO Neo9 Pro" 示例 → 错误命中）
        // 严格遵循 SSOT：宁可空 picks，也不推荐无关商品
        if (result.picks.length === 0 && originalJsonPicks.length > 0) {
          console.warn('⚠️ Coze 所有 picks ID 均不在目录中（幻觉），按 SSOT 返回空 picks');
        }
        
        if (result.picks.length > 0) {
          result.intent = "SHOPPING";
        }
      }
    }
  } catch (e) {
    console.log('📝 未找到 JSON picks');
  }

  // 仅保留严格的 [ID:xxx] 引用匹配（必须是目录中真实存在的完整 UUID）
  if (result.picks.length === 0) {
    const idPattern = /\[ID:([a-f0-9-]{36})\]/gi;
    let match;
    while ((match = idPattern.exec(text)) !== null) {
      const productId = match[1];
      const product = catalog.find(c => c.id === productId);
      if (product) {
        result.picks.push({
          product_id: productId,
          note: product.name,
          source: 'coze-id-ref'
        });
      }
    }
    // ❌ 不再做"产品名/价格"文本兜底匹配 —— 这是幻觉放大器
    
    if (result.picks.length === 0 && result.intent === 'SHOPPING') {
      console.error('❌ Coze 返回了无效的产品推荐（所有 ID 都不在目录中）');
    }
  }

  // 提取高亮句子
  const sentences = text.split(/[。！？\n]/).filter(s => s.length > 10 && s.length < 100);
  result.highlights = sentences.slice(0, 3);

  console.log('📊 解析结果:', { 
    intent: result.intent, 
    picksCount: result.picks.length,
    sources: [...new Set(result.picks.map(p => p.source))]
  });

  return result;
}

// 调用 Coze API
async function callCozeAPI(
  message: string, 
  userInfo: any, 
  catalog: any[], 
  conversationId?: string,
  userContext?: string
): Promise<CozeResponse> {
  const COZE_API_KEY = Deno.env.get('COZE_API_KEY') || Deno.env.get('COZE_API_TOKEN');
  const COZE_WORKFLOW_URL = Deno.env.get('COZE_WORKFLOW_URL') || 'https://dbwbtkkt9g.coze.site/stream_run';
  
  if (!COZE_API_KEY) {
    console.error('❌ Missing COZE_API_KEY');
    throw new Error('COZE_UNAVAILABLE');
  }

  try {
    // 动态获取 Agent 规范
    const agentSpec = await fetchAgentSpec();
    const systemPrompt = buildSystemPrompt(agentSpec, userInfo, catalog, userContext);
    
    console.log('🚀 Calling Coze Workflow API:', { 
      url: COZE_WORKFLOW_URL,
      userId: userInfo.id,
      catalogCount: catalog.length,
      hasUserContext: !!userContext,
      agentName: agentSpec.persona?.name || 'unknown'
    });
    
    const controller = new AbortController();
    const timeoutId = setTimeout(() => controller.abort(), 60000);
    
    // 构建包含上下文的完整查询
    const catalogSummary = catalog.slice(0, 20).map(p => 
      `[ID:${p.id}] ${p.name} ¥${p.price}`
    ).join('\n');
    
    const fullQuery = `${systemPrompt}

## 用户问题
${message}

## 可用产品（前20个）
${catalogSummary}`;

    const requestBody = {
      text: fullQuery
    };

    let response;
    try {
      response = await fetch(COZE_WORKFLOW_URL, {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${COZE_API_KEY}`,
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(requestBody),
        signal: controller.signal,
      });
    } finally {
      clearTimeout(timeoutId);
    }

    if (!response.ok) {
      const errorText = await response.text();
      console.error('❌ Coze Workflow error:', response.status, errorText.substring(0, 500));
      throw new Error('COZE_UNAVAILABLE');
    }

    // 处理 SSE 流式响应
    const responseText = await response.text();
    console.log('✅ Coze Workflow response received, length:', responseText.length);
    
    let answer = '';
    const lines = responseText.split('\n');
    
    for (const line of lines) {
      if (!line.trim() || line.startsWith(':')) continue;
      
      if (line.startsWith('data:')) {
        const jsonStr = line.slice(5).trim();
        if (jsonStr === '[DONE]') continue;
        
        try {
          const parsed = JSON.parse(jsonStr);
          // 支持多种响应格式
          const content = parsed.answer || 
                         parsed.content?.answer || 
                         parsed.data?.answer ||
                         parsed.choices?.[0]?.delta?.content ||
                         parsed.choices?.[0]?.message?.content ||
                         '';
          if (content) {
            answer += content;
          }
        } catch (e) {
          // 可能是非 JSON 行，跳过
          console.log('📝 Non-JSON SSE line:', line.substring(0, 100));
        }
      } else {
        // 尝试直接解析非 data: 前缀的行
        try {
          const parsed = JSON.parse(line);
          const content = parsed.answer || parsed.content?.answer || parsed.data?.answer || '';
          if (content) answer += content;
        } catch {
          // 忽略
        }
      }
    }
    
    if (!answer) {
      // 如果 SSE 解析失败，尝试整体解析
      try {
        const fullData = JSON.parse(responseText);
        answer = fullData.answer || fullData.data?.answer || fullData.content?.answer || '';
      } catch {
        answer = '抱歉，我暂时无法回答您的问题';
      }
    }
    
    const parsed = parseTextResponse(answer, catalog, message);
    
    return {
      title: message.substring(0, 50),
      intent: parsed.intent,
      sentiment: 'NEUTRAL',
      highlights: parsed.highlights,
      picks: parsed.picks,
      next: ['继续咨询', '查看详情'],
      meta: {
        platform: 'coze-workflow',
        user: userInfo.id,
        catalog_count: catalog.length,
        probe_id: crypto.randomUUID()
      },
      answer,
      conversation_id: conversationId || ''
    };
    
  } catch (error) {
    console.error('❌ Coze Workflow error:', error);
    throw error;
  }
}

// Lovable AI 备用方案
async function callLovableAI(message: string, userInfo: any, catalog: any[]): Promise<CozeResponse> {
  const LOVABLE_API_KEY = Deno.env.get('LOVABLE_API_KEY');
  
  if (!LOVABLE_API_KEY) {
    throw new Error('备用AI服务未配置');
  }
  
  console.log('🔄 Falling back to Lovable AI Gateway...');
  
  const agentSpec = await fetchAgentSpec();
  const systemPrompt = buildSystemPrompt(agentSpec, userInfo, catalog);

  const response = await fetch(_AI_CHAT_URL, {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${_AI_CHAT_KEY}`,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      model: _mapAiModel('google/gemini-2.5-flash'),
      messages: [
        { role: 'system', content: systemPrompt },
        { role: 'user', content: message }
      ],
      max_tokens: 1000,
    }),
  });

  if (!response.ok) {
    throw new Error(`Lovable AI 响应错误 (${response.status})`);
  }

  const data = await response.json();
  const answer = data.choices?.[0]?.message?.content || '抱歉，我暂时无法回答您的问题';
  
  const parsed = parseTextResponse(answer, catalog, message);
  
  return {
    title: message.substring(0, 50),
    intent: parsed.intent,
    sentiment: 'NEUTRAL',
    highlights: parsed.highlights,
    picks: parsed.picks,
    next: ['继续咨询', '查看详情'],
    meta: {
      platform: 'lovable-fallback',
      user: userInfo.id,
      catalog_count: catalog.length,
      probe_id: crypto.randomUUID()
    },
    answer,
    conversation_id: undefined
  };
}

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

  const traceId = req.headers.get('x-trace-id') || crypto.randomUUID();
  
  try {
    const body: CozeRequest = await req.json();
    const { message, conversationId, inputs } = body;
    
    console.log('📥 coze-chat request:', {
      trace_id: traceId,
      message: message?.substring(0, 50),
      conversationId: conversationId || '(new)',
      catalogCount: inputs?.catalog?.length || 0
    });

    const supabaseUrl = Deno.env.get('SUPABASE_URL')!;
    const supabaseKey = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
    const supabase = createClient(supabaseUrl, supabaseKey);

    let userInfo = { id: inputs.user_id || 'anonymous', email: '' };
    
    // 只有当 user_id 看起来像 UUID 时才查询用户信息
    const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
    if (inputs.user_id && uuidRegex.test(inputs.user_id)) {
      const { data: userData } = await supabase.auth.admin.getUserById(inputs.user_id);
      if (userData?.user) {
        userInfo = {
          id: userData.user.id,
          email: userData.user.email || ''
        };
      }
    }

    let catalog = inputs.catalog || [];
    if (catalog.length === 0) {
      const { data: products } = await supabase
        .from('products')
        .select('id, name, price, stock_quantity, category, description')
        .eq('is_active', true)
        .limit(50);
      catalog = products || [];
    }

    let response: CozeResponse;
    
    try {
      response = await callCozeAPI(
        message, 
        userInfo, 
        catalog, 
        conversationId,
        inputs.user_context
      );
    } catch (error) {
      console.log('⚠️ Coze 不可用，切换到 Lovable AI...');
      response = await callLovableAI(message, userInfo, catalog);
    }

    console.log('📤 coze-chat response:', {
      trace_id: traceId,
      platform: response.meta.platform,
      intent: response.intent,
      picks: response.picks.length,
      conversation_id: response.conversation_id || '(none)'
    });

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

  } catch (error) {
    console.error('❌ coze-chat error:', error);
    
    return new Response(JSON.stringify({
      title: '系统繁忙',
      intent: 'GENERAL',
      sentiment: 'NEUTRAL',
      highlights: [],
      picks: [],
      next: ['重新发送'],
      meta: {
        platform: 'error',
        user: 'unknown',
        catalog_count: 0,
        probe_id: traceId
      },
      answer: '抱歉，系统暂时繁忙，请稍后再试',
      error: (error instanceof Error ? error.message : '未知错误')
    }), {
      status: 500,
      headers: { ...corsHeaders, 'Content-Type': 'application/json' }
    });
  }
});
