import { serve } from "https://deno.land/std@0.168.0/http/server.ts";
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` : _AI_CHAT_URL;
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",
};

/**
 * Coze Langchain GenUI Agent
 * 
 * 统一的 AI 入口：
 * 1. 注入 GenUI 组件库规范
 * 2. 根据意图识别注入对应部门的实时数据上下文
 * 3. 调用 Coze LangChain Agent 生成 UI Schema
 * 4. 失败时降级到 Lovable AI Gateway
 */

// ========================
// GenUI 组件库定义 (供 Coze Agent 参考)
// ========================

const GENUI_COMPONENT_LIBRARY = `
你是智能电商管理助手，需要根据用户查询动态生成 UI Schema 供前端渲染。

## 可用组件库

**重要**: 每个组件必须包含 type 和 props 两个字段，所有属性都放在 props 内部！

### stats_row - 统计指标行
用于展示多个关键数字指标
{ "type": "stats_row", "props": { "items": [{ "label": "标签", "value": "值或数字", "color": "success|warning|error|info|default" }] } }

### data_table - 数据表格
用于展示列表数据，如订单、商品、用户等
{ 
  "type": "data_table", 
  "props": { 
    "title": "表格标题",
    "columns": [{ "key": "字段名", "label": "列标题" }],
    "rows": [{ "字段名": "值" }]
  } 
}

### chart - 图表
用于数据可视化
{ "type": "chart", "props": { "title": "图表标题", "type": "pie|bar|line|area", "data": [{ "label": "分类", "value": 数值 }] } }

### alert - 警告/提示
用于重要信息提示
{ "type": "alert", "props": { "type": "error|warning|info|success", "title": "标题", "description": "描述" } }

### insight_card - 洞察卡片
用于 AI 建议和分析
{ "type": "insight_card", "props": { "type": "warning|success|opportunity|info", "title": "标题", "description": "描述", "metric": { "label": "指标", "value": "值" } } }

### progress_bar - 进度条
{ "type": "progress_bar", "props": { "label": "进度名", "current": 当前值, "target": 目标值 } }

### text - 文本块
{ "type": "text", "props": { "content": "文本内容", "variant": "h1|h2|h3|body|caption" } }

### insight_feed - 洞察流
用于展示多条洞察/建议列表
{ "type": "insight_feed", "props": { "title": "洞察列表", "insights": [{ "id": "唯一ID", "type": "warning|success|info", "title": "标题", "description": "描述" }] } }

### approval_list - 审批列表
用于展示待审批事项
{ "type": "approval_list", "props": { "title": "审批列表", "approvals": [{ "id": "唯一ID", "type": "marketing|product", "title": "标题", "description": "描述", "agent": "发起人", "priority": "high|medium|low" }] } }

## 输出格式（严格遵循此 JSON 结构）

{
  "answer": "对用户问题的简洁回答",
  "ui_schema": {
    "layout": "vertical",
    "gap": "md",
    "components": [
      { "type": "组件类型", "props": { ... } }
    ]
  },
  "suggested_actions": ["建议操作1", "建议操作2"]
}

## 核心规则
1. 每个组件必须有 type 和 props 两个字段
2. 所有属性（如 title、columns、rows）都必须放在 props 内部，不能放在顶层
3. 使用数据上下文中提供的真实数据填充组件
4. 保持界面简洁，最多 6 个组件
5. 优先用 alert 展示异常和预警信息
6. 回答要简洁专业，面向管理者
`;

// ========================
// 意图识别
// ========================

type AgentType = 'manager' | 'product' | 'marketing' | 'finance' | 'service';

const INTENT_KEYWORDS: Record<AgentType, string[]> = {
  manager: ['全局', '总览', '店铺概览', '经营概况', '整体', '审批', '团队', 'KPI', '绩效', '客户', '用户列表', '客户信息'],
  product: ['商品', '产品', '库存', '上架', '下架', '缺货', '补货', '分类', '品牌', '热销', '滞销', '手机', '电脑'],
  marketing: ['营销', '促销', '活动', '优惠券', '秒杀', '拼团', '广告', '推广', '折扣', 'ROI', '转化'],
  finance: ['财务', '收入', '支出', '利润', '销售额', '营收', '收款', '退款', '会员', '报表', '账单'],
  service: ['售后', '客服', '工单', '投诉', '退换货', '退货', '换货', '发货', '物流', '差评'],
};

function detectAgentType(message: string): AgentType {
  const lowerMsg = message.toLowerCase();
  let bestMatch: AgentType = 'manager';
  let maxMatches = 0;

  for (const [agentType, keywords] of Object.entries(INTENT_KEYWORDS) as [AgentType, string[]][]) {
    const matches = keywords.filter(kw => lowerMsg.includes(kw.toLowerCase())).length;
    if (matches > maxMatches) {
      maxMatches = matches;
      bestMatch = agentType;
    }
  }

  console.log(`[CozeLangchain] Detected agent type: ${bestMatch} (matches: ${maxMatches})`);
  return bestMatch;
}

function getAgentDisplayName(agentType: AgentType): string {
  const names: Record<AgentType, string> = {
    manager: '店铺经理(小管)',
    product: '商品经理(小品)',
    marketing: '营销经理(小营)',
    finance: '财务经理(小财)',
    service: '客服经理(小服)',
  };
  return names[agentType] || agentType;
}

// ========================
// 数据获取层
// ========================

async function fetchDataContext(supabase: any, agentType: AgentType): Promise<string> {
  const now = new Date();
  const monthStart = new Date(now.getFullYear(), now.getMonth(), 1).toISOString();
  const weekStart = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000).toISOString();

  let context = '';

  try {
    // 基础数据 - 所有 Agent 都需要
    const [ordersResult, productsResult, profilesResult] = await Promise.all([
      supabase.from('orders').select('id, total_amount, status, created_at').gte('created_at', monthStart).order('created_at', { ascending: false }).limit(500),
      supabase.from('products').select('id, name, stock_quantity, monthly_sales, is_active, price', { count: 'exact' }).eq('is_active', true),
      supabase.from('profiles').select('id, user_id, display_name, phone, role, created_at').order('created_at', { ascending: false }).limit(100),
    ]);

    const orders = ordersResult.data || [];
    const products = productsResult.data || [];
    const profiles = profilesResult.data || [];

    const thisMonthRevenue = orders.filter((o: any) => o.status !== 'cancelled').reduce((sum: number, o: any) => sum + (o.total_amount || 0), 0);
    const pendingOrders = orders.filter((o: any) => o.status === 'pending').length;
    const lowStockProducts = products.filter((p: any) => p.stock_quantity < 10);

    context = `
## 基础经营数据
- 本月营收: ¥${thisMonthRevenue.toLocaleString()}
- 订单数量: ${orders.length} 个
- 待处理订单: ${pendingOrders} 个
- 在售商品: ${products.length} 款
- 库存预警商品: ${lowStockProducts.length} 款
- 注册用户: ${profiles.length} 人
`;

    // 根据 Agent 类型补充专属数据
    if (agentType === 'manager') {
      // 用户列表数据
      const userListStr = profiles.slice(0, 20).map((p: any) => 
        `${p.display_name || '未设置'} | ${p.phone || '无'} | ${p.role || 'user'} | ${p.created_at?.split('T')[0] || ''}`
      ).join('\n');

      context += `
## 用户/客户列表 (最近20条)
姓名 | 电话 | 角色 | 注册时间
${userListStr || '暂无用户数据'}
`;

      // 审批待办
      const [campaignsResult, afterSalesResult] = await Promise.all([
        supabase.from('marketing_campaigns').select('id, name, status, type').eq('status', 'pending').limit(10),
        supabase.from('after_sales_requests').select('id, type, status').eq('status', 'pending').limit(10),
      ]);
      const pendingCampaigns = campaignsResult.data?.length || 0;
      const pendingAfterSales = afterSalesResult.data?.length || 0;

      context += `
## 待办事项
- 待审批活动: ${pendingCampaigns} 个
- 待处理售后: ${pendingAfterSales} 个
`;
    }

    if (agentType === 'product') {
      const lowStockStr = lowStockProducts.slice(0, 10).map((p: any) => 
        `${p.name} | 库存: ${p.stock_quantity} | 月销: ${p.monthly_sales || 0}`
      ).join('\n');

      const hotProducts = products.filter((p: any) => p.monthly_sales > 50).slice(0, 5);
      const hotStr = hotProducts.map((p: any) => 
        `${p.name} | 月销: ${p.monthly_sales} | ¥${p.price}`
      ).join('\n');

      context += `
## 库存预警商品
${lowStockStr || '无预警商品'}

## 热销商品 TOP5
${hotStr || '暂无热销数据'}
`;
    }

    if (agentType === 'marketing') {
      const [campaignsResult, couponsResult] = await Promise.all([
        supabase.from('marketing_campaigns').select('id, name, status, type, start_date, end_date').order('created_at', { ascending: false }).limit(10),
        supabase.from('coupons').select('id, name, status, discount_value, used_quantity, total_quantity').eq('status', 'active').limit(10),
      ]);

      const campaigns = campaignsResult.data || [];
      const coupons = couponsResult.data || [];

      const campaignStr = campaigns.map((c: any) => `${c.name} | ${c.type} | ${c.status}`).join('\n');
      const couponStr = coupons.map((c: any) => `${c.name} | 折扣: ${c.discount_value} | 已用: ${c.used_quantity}/${c.total_quantity}`).join('\n');

      context += `
## 营销活动
${campaignStr || '暂无活动'}

## 优惠券
${couponStr || '暂无优惠券'}
`;
    }

    if (agentType === 'finance') {
      // 订单状态分布
      const statusMap: Record<string, number> = {};
      orders.forEach((o: any) => { statusMap[o.status] = (statusMap[o.status] || 0) + 1; });
      const statusStr = Object.entries(statusMap).map(([k, v]) => `${k}: ${v}`).join(', ');

      const [rechargePlansResult] = await Promise.all([
        supabase.from('recharge_plans').select('id, name, recharge_amount, bonus_amount, is_active').eq('is_active', true),
      ]);

      context += `
## 订单状态分布
${statusStr}

## 充值套餐
${(rechargePlansResult.data || []).map((p: any) => `${p.name}: ¥${p.recharge_amount} + 赠 ¥${p.bonus_amount}`).join('\n') || '暂无套餐'}
`;
    }

    if (agentType === 'service') {
      const [afterSalesResult] = await Promise.all([
        supabase.from('after_sales_requests').select('id, type, status, reason, created_at').gte('created_at', weekStart).order('created_at', { ascending: false }).limit(20),
      ]);

      const afterSales = afterSalesResult.data || [];
      const pendingCount = afterSales.filter((a: any) => a.status === 'pending').length;
      const typeMap: Record<string, number> = {};
      afterSales.forEach((a: any) => { typeMap[a.type] = (typeMap[a.type] || 0) + 1; });

      context += `
## 售后工单 (本周)
- 总工单: ${afterSales.length} 个
- 待处理: ${pendingCount} 个
- 类型分布: ${Object.entries(typeMap).map(([k, v]) => `${k}: ${v}`).join(', ')}
`;
    }

  } catch (error) {
    console.error('[CozeLangchain] Error fetching data context:', error);
    context = '数据获取失败，请稍后重试。';
  }

  return context;
}

// ========================
// Coze API 调用
// ========================

interface CozeLangchainRequest {
  text: string;
  stream?: boolean;
  session_id?: string;
  agent_type?: AgentType;
  skip_data_context?: boolean; // 跳过数据注入（用于简单对话）
}

interface GenUIResponse {
  answer: string;
  ui_schema?: {
    layout: string;
    gap?: string;
    components: any[];
  };
  suggested_actions?: string[];
}

const COZE_API_URL = "https://dbwbtkkt9g.coze.site/stream_run";
const COZE_PROJECT_ID = "7602899003382071342";

async function callCozeAgent(
  text: string,
  sessionId: string,
  dataContext: string,
  agentType: AgentType
): Promise<GenUIResponse> {
  const COZE_API_TOKEN = Deno.env.get("COZE_API_TOKEN");
  if (!COZE_API_TOKEN) {
    throw new Error("COZE_API_TOKEN 未配置");
  }

  // 构建增强 Prompt
  const enhancedPrompt = `${GENUI_COMPONENT_LIBRARY}

## 当前数据上下文
${dataContext}

## 用户问题
${text}

请根据以上信息生成 JSON 响应。`;

  const cozeRequestBody = {
    content: {
      query: {
        prompt: [{ type: "text", content: { text: enhancedPrompt } }]
      }
    },
    type: "query",
    session_id: sessionId,
    project_id: COZE_PROJECT_ID
  };

  console.log(`[CozeLangchain] Calling Coze API for ${agentType}...`);

  const response = await fetch(COZE_API_URL, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "Authorization": `Bearer ${COZE_API_TOKEN}`,
    },
    body: JSON.stringify(cozeRequestBody),
  });

  if (!response.ok) {
    const errorText = await response.text();
    console.error(`[CozeLangchain] Coze API error: ${errorText}`);
    throw new Error(`Coze API 调用失败 (${response.status})`);
  }

  // 解析 SSE 响应
  const responseText = await response.text();
  console.log(`[CozeLangchain] Raw response length: ${responseText.length}`);
  
  // 打印前500字符用于调试
  console.log(`[CozeLangchain] Raw response preview: ${responseText.substring(0, 500)}`);

  // 提取 answer 内容 - 支持多种 Coze 响应格式
  let fullAnswer = '';
  const lines = responseText.split('\n');
  
  for (const line of lines) {
    const trimmedLine = line.trim();
    
    // 跳过空行和事件行
    if (!trimmedLine || trimmedLine.startsWith('event:') || trimmedLine.startsWith(':')) {
      continue;
    }
    
    // 提取 data: 后的内容
    let dataContent = trimmedLine;
    if (trimmedLine.startsWith('data:')) {
      dataContent = trimmedLine.slice(5).trim();
    }
    
    if (!dataContent || dataContent === '[DONE]') {
      continue;
    }
    
    try {
      const data = JSON.parse(dataContent);
      
      // 格式1: { type: 'answer', content: { answer: '...' } }
      if (data.type === 'answer' && data.content?.answer) {
        fullAnswer += data.content.answer;
      }
      // 格式2: { content: { answer: '...' } }
      else if (data.content?.answer) {
        fullAnswer += data.content.answer;
      }
      // 格式3: { content: { thinking: '...' } } - 思考过程
      else if (data.content?.thinking) {
        console.log(`[CozeLangchain] Received thinking: ${data.content.thinking.substring(0, 100)}...`);
      }
      // 格式4: { answer: '...' } - 直接 answer 字段
      else if (data.answer) {
        fullAnswer += data.answer;
      }
      // 格式5: 直接文本 { text: '...' } 或 { output: '...' }
      else if (data.text) {
        fullAnswer += data.text;
      } else if (data.output) {
        fullAnswer += data.output;
      }
      // 格式6: message_end - 结束标记，检查是否有错误
      else if (data.type === 'message_end' && data.content?.message_end) {
        const msgEnd = data.content.message_end;
        if (msgEnd.code !== '0' && msgEnd.code !== 0 && msgEnd.message) {
          console.error(`[CozeLangchain] Coze error: ${msgEnd.message}`);
        }
      }
    } catch {
      // 如果解析 JSON 失败，检查是否是纯文本内容
      if (dataContent && !dataContent.startsWith('{') && !dataContent.startsWith('[')) {
        // 可能是纯文本回复
        fullAnswer += dataContent;
      }
    }
  }

  console.log(`[CozeLangchain] Extracted answer length: ${fullAnswer.length}`);
  if (fullAnswer.length > 0) {
    console.log(`[CozeLangchain] Answer preview: ${fullAnswer.substring(0, 200)}...`);
  }

  // 尝试解析 JSON（如果 answer 是 JSON 格式）
  try {
    // 尝试从回答中提取 JSON
    let jsonContent = fullAnswer.trim();
    
    // 检查是否包含 markdown 代码块
    const jsonMatch = jsonContent.match(/```(?:json)?\s*([\s\S]*?)```/);
    if (jsonMatch) {
      jsonContent = jsonMatch[1].trim();
    }

    // 尝试找到 JSON 对象
    const jsonStart = jsonContent.indexOf('{');
    const jsonEnd = jsonContent.lastIndexOf('}');
    if (jsonStart !== -1 && jsonEnd !== -1 && jsonStart < jsonEnd) {
      jsonContent = jsonContent.substring(jsonStart, jsonEnd + 1);
      
      const parsed = JSON.parse(jsonContent);
      
      // 确保 ui_schema 结构正确
      let uiSchema = parsed.ui_schema;
      if (uiSchema && uiSchema.components) {
        // 验证组件格式
        uiSchema.components = uiSchema.components.map((comp: any) => {
          // 确保每个组件都有 type 和 props
          if (comp.type && !comp.props) {
            const { type, ...rest } = comp;
            return { type, props: rest };
          }
          return comp;
        });
      }
      
      console.log(`[CozeLangchain] Parsed JSON successfully, has ui_schema: ${!!uiSchema}`);
      
      return {
        answer: parsed.answer || '已为您生成界面',
        ui_schema: uiSchema,
        suggested_actions: parsed.suggested_actions,
      };
    }
  } catch (parseError) {
    console.log(`[CozeLangchain] JSON parse failed: ${parseError}`);
  }
  
  // 如果无法解析为 JSON，返回纯文本
  return {
    answer: fullAnswer || '抱歉，无法解析响应内容。请检查 Coze Agent 配置。',
  };
}

// ========================
// Lovable AI Gateway 降级
// ========================

async function callLovableAIFallback(
  text: string,
  dataContext: string,
  agentType: AgentType
): Promise<GenUIResponse> {
  const LOVABLE_AI_URL = _AI_CHAT_URL;
  const LOVABLE_AI_KEY = Deno.env.get('LOVABLE_API_KEY');

  if (!LOVABLE_AI_KEY) {
    console.log('[CozeLangchain] LOVABLE_API_KEY not set, returning text only');
    return { answer: '当前 AI 服务不可用，请稍后再试。' };
  }

  console.log(`[CozeLangchain] Falling back to Lovable AI Gateway for ${agentType}`);

  const systemPrompt = `${GENUI_COMPONENT_LIBRARY}

## 当前数据上下文
${dataContext}

请根据用户问题和数据，生成合适的 UI Schema 和回答。`;

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

  if (!response.ok) {
    throw new Error(`Lovable AI 调用失败: ${response.status}`);
  }

  const result = await response.json();
  const content = result.choices?.[0]?.message?.content;

  if (!content) {
    return { answer: 'AI 返回内容为空' };
  }

  // 解析 JSON
  let jsonContent = content.trim();
  const jsonMatch = jsonContent.match(/```(?:json)?\s*([\s\S]*?)```/);
  if (jsonMatch) jsonContent = jsonMatch[1].trim();

  try {
    const parsed = JSON.parse(jsonContent);
    return {
      answer: parsed.answer || '已为您生成界面',
      ui_schema: parsed.ui_schema,
      suggested_actions: parsed.suggested_actions,
    };
  } catch {
    return { answer: content };
  }
}

// ========================
// 主处理函数
// ========================

serve(async (req) => {
  const traceId = crypto.randomUUID();
  
  if (req.method === "OPTIONS") {
    return new Response(null, { headers: corsHeaders });
  }

  try {
    console.log(`[CozeLangchain] Request received: ${traceId}`);

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

    const body: CozeLangchainRequest = await req.json();
    const { text, stream = false, session_id, agent_type, skip_data_context = false } = body;

    if (!text || typeof text !== "string") {
      throw new Error("text 参数是必填的字符串");
    }

    // 意图识别
    const detectedAgentType = agent_type || detectAgentType(text);
    const currentSessionId = session_id || `session_${crypto.randomUUID().replace(/-/g, '').substring(0, 20)}`;

    console.log(`[CozeLangchain] Processing: agent=${detectedAgentType}, session=${currentSessionId}`);

    // 获取数据上下文
    let dataContext = '';
    if (!skip_data_context) {
      dataContext = await fetchDataContext(supabase, detectedAgentType);
      console.log(`[CozeLangchain] Data context length: ${dataContext.length}`);
    }

    let result: GenUIResponse;
    let usedFallback = false;

    // 尝试调用 Coze Agent
    try {
      result = await callCozeAgent(text, currentSessionId, dataContext, detectedAgentType);
      console.log(`[CozeLangchain] Coze succeeded, has ui_schema: ${!!result.ui_schema}`);
      
      // 如果 Coze 返回空内容或默认错误消息，主动降级
      const isEmpty = !result.answer || 
                      result.answer.includes('无法解析响应内容') ||
                      result.answer.includes('请检查 Coze Agent');
      
      if (isEmpty && !result.ui_schema) {
        console.warn(`[CozeLangchain] Coze returned empty content, forcing fallback`);
        throw new Error('Coze returned empty content');
      }
    } catch (cozeError) {
      console.error(`[CozeLangchain] Coze failed, falling back:`, cozeError);
      usedFallback = true;
      
      // 降级到 Lovable AI Gateway
      try {
        result = await callLovableAIFallback(text, dataContext, detectedAgentType);
        console.log(`[CozeLangchain] Fallback succeeded, has ui_schema: ${!!result.ui_schema}`);
      } catch (fallbackError) {
        console.error(`[CozeLangchain] Fallback also failed:`, fallbackError);
        // 最终降级 - 返回基础文本
        result = {
          answer: `抱歉，AI 服务暂时不可用。您查询的是 ${getAgentDisplayName(detectedAgentType)} 相关内容，请稍后再试。`,
        };
      }
    }

    // 返回响应
    const response = {
      success: true,
      ...result,
      agent_type: detectedAgentType,
      session_id: currentSessionId,
      trace_id: traceId,
    };

    return new Response(JSON.stringify(response), {
      headers: { 
        ...corsHeaders, 
        "Content-Type": "application/json",
        "X-Trace-Id": traceId,
        "X-Agent-Type": detectedAgentType,
      },
    });

  } catch (error) {
    console.error(`[CozeLangchain] Error:`, error);

    return new Response(JSON.stringify({
      success: false,
      error: (error instanceof Error ? error.message : "Unknown error"),
      trace_id: traceId,
    }), {
      status: 400,
      headers: { ...corsHeaders, "Content-Type": "application/json" },
    });
  }
});
