/**
 * GenUI 路由服务
 * 
 * 根据用户自然语言输入识别意图，路由到对应的 GenUI Edge Function
 */

import { supabase } from '@/integrations/supabase/client';

// GenUI Agent 类型
export type GenUIAgentType = 'manager' | 'product' | 'marketing' | 'finance' | 'service';

// 意图关键词映射到 Agent 类型
const INTENT_KEYWORDS: Record<GenUIAgentType, string[]> = {
  manager: [
    // 全局/总览
    '全局', '总览', '店铺概览', '经营概况', '整体情况', '业务总览',
    '跨部门', '协调', '全局分析', '综合分析',
    '目标', 'KPI', '业绩', '考核', '绩效',
    '审批中心', '待办事项', '审批列表',
    '团队', '员工', '人员',
  ],
  product: [
    // 商品相关
    '商品', '产品', '库存', '货品', '物品',
    '上架', '下架', '商品列表', '商品管理',
    '缺货', '低库存', '补货', '库存预警', '库存不足',
    '分类', '品类', '类目', '商品分类',
    '品牌', '品牌管理', '品牌列表',
    '新品', '新上架', '最新商品',
    '热销', '爆款', '畅销', '热门商品',
    '商品分析', '商品报表', '销量排行',
    // 具体品类
    '手机', '电脑', '平板', '数码', '电子产品',
    // 动销/滞销
    '滞销', '卖得慢', '卖不动', '动销', '周转',
  ],
  marketing: [
    // 营销相关
    '营销', '促销', '活动', '推广', '运营',
    '优惠券', '券', '折扣券', '满减券', '发券',
    '秒杀', '限时', '闪购', '抢购',
    '拼团', '团购', '组团',
    '营销分析', '活动效果', 'ROI', '转化率',
    '用户增长', '拉新', '留存', '复购',
    '广告', '投放', '推广费用',
  ],
  finance: [
    // 财务相关
    '财务', '收入', '支出', '利润', '成本',
    '销售额', '营收', '收款', '付款', '结算',
    '订单统计', '交易', '流水', '账单',
    '退款', '退货统计', '退款分析',
    '会员', 'VIP', '会员分析', '会员等级',
    '财务报表', '收支报表', '财务分析',
  ],
  service: [
    // 客服相关
    '售后', '客服', '服务', '工单', '投诉',
    '退换货', '退货', '换货', '维修',
    '待发货', '发货', '物流', '快递',
    '客诉', '差评', '评价', '反馈',
    '客户问题', '用户投诉', '服务质量',
  ],
};

// 意图识别结果
export interface GenUIIntentResult {
  agentType: GenUIAgentType;
  confidence: number;
  matchedKeywords: string[];
}

/**
 * 识别用户意图，返回对应的 GenUI Agent 类型
 */
export function recognizeGenUIIntent(message: string): GenUIIntentResult {
  const lowerMessage = message.toLowerCase();
  
  let bestMatch: GenUIIntentResult = {
    agentType: 'manager',
    confidence: 0.3,
    matchedKeywords: [],
  };

  for (const [agentType, keywords] of Object.entries(INTENT_KEYWORDS) as [GenUIAgentType, string[]][]) {
    const matched = keywords.filter(kw => lowerMessage.includes(kw.toLowerCase()));
    
    if (matched.length > bestMatch.matchedKeywords.length) {
      bestMatch = {
        agentType,
        confidence: Math.min(0.95, 0.5 + matched.length * 0.15),
        matchedKeywords: matched,
      };
    }
  }

  console.log('[GenUI Router] Intent recognized:', bestMatch);
  return bestMatch;
}

// GenUI 响应类型
export interface GenUIResponse {
  answer: string;
  ui_schema?: {
    version: string;
    layout: string;
    gap?: string;
    components: any[];
  };
  insights?: Array<{
    id: string;
    type: string;
    title: string;
    description: string;
    action?: any;
  }>;
  suggested_actions?: string[];
  conversation_id?: string;
  error?: boolean;
  message?: string;
}

/**
 * 调用 GenUI Edge Function
 */
/**
 * 调用 GenUI Edge Function
 * 优先使用 Coze LangChain Agent，失败时降级到原有的部门 GenUI 函数
 */
export async function callGenUI(
  agentType: GenUIAgentType,
  message: string,
  context?: {
    current_page?: string;
    conversation_id?: string;
    selected_items?: string[];
    filters?: Record<string, any>;
  }
): Promise<GenUIResponse> {
  console.log(`[GenUI Router] Calling with agent type: ${agentType}, message:`, message);
  
  // 优先尝试 Coze LangChain Agent (统一入口)
  try {
    const { data, error } = await supabase.functions.invoke('coze-langchain', {
      body: {
        text: message,
        agent_type: agentType,
        session_id: context?.conversation_id,
      },
    });

    if (error) {
      console.warn(`[GenUI Router] Coze LangChain error, falling back:`, error);
      throw error;
    }

    if (data?.success) {
      console.log(`[GenUI Router] Coze LangChain succeeded, has ui_schema:`, !!data.ui_schema);
      return {
        answer: data.answer || '',
        ui_schema: data.ui_schema,
        suggested_actions: data.suggested_actions,
        conversation_id: data.session_id,
      };
    }

    // 如果 Coze 返回失败，降级
    console.warn(`[GenUI Router] Coze returned error:`, data?.error);
    throw new Error(data?.error || 'Coze response error');

  } catch (cozeErr) {
    console.warn(`[GenUI Router] Coze failed, trying fallback to ${agentType}-genui`);
    
    // 降级到原有的部门 GenUI 函数
    const functionName = `${agentType}-genui`;
    
    try {
      const { data, error } = await supabase.functions.invoke(functionName, {
        body: {
          message,
          conversation_id: context?.conversation_id,
          context: {
            current_page: context?.current_page,
            selected_items: context?.selected_items,
            filters: context?.filters,
          },
        },
      });

      if (error) {
        console.error(`[GenUI Router] Fallback ${functionName} also failed:`, error);
        return {
          answer: `抱歉，${getAgentName(agentType)}暂时无法响应，请稍后再试。`,
          error: true,
          message: error.message,
        };
      }

      console.log(`[GenUI Router] Fallback ${functionName} succeeded`);
      return data as GenUIResponse;

    } catch (fallbackErr) {
      console.error(`[GenUI Router] All attempts failed:`, fallbackErr);
      return {
        answer: '系统错误，请稍后重试。',
        error: true,
        message: fallbackErr instanceof Error ? fallbackErr.message : '未知错误',
      };
    }
  }
}

/**
 * 自动路由并调用 GenUI
 */
export async function routeAndCallGenUI(
  message: string,
  context?: {
    current_page?: string;
    conversation_id?: string;
    selected_items?: string[];
    filters?: Record<string, any>;
    forceAgent?: GenUIAgentType; // 强制指定 Agent
  }
): Promise<GenUIResponse & { agentType: GenUIAgentType }> {
  // 如果强制指定了 Agent，直接使用
  const agentType = context?.forceAgent || recognizeGenUIIntent(message).agentType;
  
  const response = await callGenUI(agentType, message, context);
  
  return {
    ...response,
    agentType,
  };
}

/**
 * 获取 Agent 中文名称
 */
export function getAgentName(agentType: GenUIAgentType): string {
  const names: Record<GenUIAgentType, string> = {
    manager: '店铺经理(小管)',
    product: '商品经理(小品)',
    marketing: '营销经理(小营)',
    finance: '财务经理(小财)',
    service: '客服经理(小服)',
  };
  return names[agentType];
}

/**
 * 获取 Agent 图标名称
 */
export function getAgentIcon(agentType: GenUIAgentType): string {
  const icons: Record<GenUIAgentType, string> = {
    manager: 'Crown',
    product: 'Package',
    marketing: 'Megaphone',
    finance: 'Wallet',
    service: 'Headphones',
  };
  return icons[agentType];
}

/**
 * 获取 Agent 颜色
 */
export function getAgentColor(agentType: GenUIAgentType): string {
  const colors: Record<GenUIAgentType, string> = {
    manager: 'bg-purple-500',
    product: 'bg-blue-500',
    marketing: 'bg-orange-500',
    finance: 'bg-green-500',
    service: 'bg-pink-500',
  };
  return colors[agentType];
}
