/**
 * 客服版块 Gen UI Edge Function
 * AI 驱动的动态 UI 生成 - 使用 Lovable AI Gateway 动态生成 Schema
 */

import { createClient } from 'https://esm.sh/@supabase/supabase-js@2.57.4';
import { getModelForPurpose } from "../_shared/modelConfig.ts";

// === 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',
};

// ========================
// 类型定义
// ========================

interface GenUIRequest {
  message: string;
  conversation_id?: string;
  context?: {
    current_view?: string;
    selected_id?: string;
    filters?: Record<string, string>;
  };
}

interface UIComponent {
  id?: string;
  type: string;
  props: Record<string, unknown>;
}

interface UISchema {
  version?: string;
  layout?: 'vertical' | 'horizontal' | 'grid';
  gap?: 'sm' | 'md' | 'lg';
  components: UIComponent[];
}

interface ServiceInsight {
  id: string;
  type: 'warning' | 'success' | 'opportunity' | 'alert' | 'info';
  priority: 'low' | 'medium' | 'high' | 'urgent';
  category: 'service' | 'customer' | 'order';
  title: string;
  description: string;
  timestamp: string;
  metric?: { label: string; value: string | number; trend?: 'up' | 'down' | 'neutral' };
  progress?: { current: number; target: number; label?: string };
  action?: { label: string; type?: 'primary' | 'secondary' };
}

interface GenUIResponse {
  answer: string;
  ui_schema?: UISchema;
  insights?: ServiceInsight[];
  conversation_id?: string;
  message_id?: string;
  suggested_actions?: string[];
  error?: string;
}

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

const GENUI_COMPONENT_LIBRARY = `
你是客服管理 AI 助手（小服），负责根据用户查询动态生成 UI Schema。

## 可用组件库

### stats_row - 统计指标行
用于展示关键数字指标
props: { items: [{ label: string, value: string|number, color?: 'info'|'warning'|'success'|'muted'|'error' }] }

### data_table - 数据表格
用于展示列表数据
props: { 
  title?: string,
  columns: [{ key: string, label: string, type?: 'status'|'date', align?: 'left'|'center'|'right' }],
  rows: [{ [key]: any }],
  maxRows?: number
}

### chart - 图表
用于数据可视化
props: { title?: string, type: 'pie'|'bar'|'line', data: [{ label: string, value: number }], height?: number }

### alert - 警告/提示
用于重要信息提示
props: { type: 'error'|'warning'|'info'|'success', title: string, description?: string }

### insight_card - 洞察卡片
用于 AI 建议
props: { type: 'warning'|'success'|'opportunity'|'info', title: string, description: string, metric?: { label: string, value: string } }

### progress_bar - 进度条
props: { label: string, current: number, target: number, color?: string }

## 输出格式

返回 JSON 格式:
{
  "answer": "对用户问题的文字回复",
  "ui_schema": {
    "layout": "vertical",
    "gap": "md",
    "components": [...]
  },
  "suggested_actions": ["建议操作1", "建议操作2"]
}

## 规则
1. 根据数据情况选择合适的组件组合
2. 优先展示用户关心的核心指标
3. 如有异常数据（如待处理售后多、待发货多）优先用 alert 提示
4. 保持界面简洁，最多 5 个组件
`;

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

async function fetchServiceData(supabase: any, context?: GenUIRequest['context']) {
  console.log('[Service GenUI] Fetching service data...', context);

  const [afterSalesRes, ordersRes, usersRes] = await Promise.all([
    supabase.from('after_sales_requests').select('*, orders(order_number, total_amount, status), products(name, image_url, price)').order('created_at', { ascending: false }).limit(100),
    supabase.from('orders').select('*, order_items(id, quantity, unit_price, products(name, image_url))').order('created_at', { ascending: false }).limit(100),
    supabase.from('profiles').select('*').order('created_at', { ascending: false }).limit(50),
  ]);

  const afterSales = afterSalesRes.data || [];
  const orders = ordersRes.data || [];
  const users = usersRes.data || [];

  const afterSalesStats = {
    pending: afterSales.filter((r: any) => r.status === 'pending').length,
    processing: afterSales.filter((r: any) => r.status === 'processing').length,
    approved: afterSales.filter((r: any) => r.status === 'approved').length,
    completed: afterSales.filter((r: any) => r.status === 'completed').length,
    rejected: afterSales.filter((r: any) => r.status === 'rejected').length,
    total: afterSales.length,
    refund: afterSales.filter((r: any) => r.type === 'refund').length,
    exchange: afterSales.filter((r: any) => r.type === 'exchange').length,
  };

  const orderStats = {
    pending: orders.filter((o: any) => o.status === 'pending').length,
    confirmed: orders.filter((o: any) => o.status === 'confirmed').length,
    shipped: orders.filter((o: any) => o.status === 'shipped').length,
    delivered: orders.filter((o: any) => o.status === 'delivered').length,
    cancelled: orders.filter((o: any) => o.status === 'cancelled').length,
    total: orders.length,
    totalRevenue: orders.reduce((sum: number, o: any) => sum + (o.total_amount || 0), 0),
  };

  console.log('[Service GenUI] Data fetched:', { afterSalesCount: afterSales.length, ordersCount: orders.length });

  const insights = generateServiceInsights(afterSalesStats, orderStats, afterSales, orders);

  return {
    afterSales,
    orders,
    users,
    afterSalesStats,
    orderStats,
    insights,
  };
}

function generateServiceInsights(afterSalesStats: any, orderStats: any, afterSales: any[], orders: any[]): ServiceInsight[] {
  const insights: ServiceInsight[] = [];
  const now = new Date();

  if (afterSalesStats.pending > 0) {
    insights.push({
      id: 'pending_aftersales',
      type: afterSalesStats.pending >= 5 ? 'alert' : 'warning',
      priority: afterSalesStats.pending >= 10 ? 'urgent' : afterSalesStats.pending >= 5 ? 'high' : 'medium',
      category: 'service',
      title: `${afterSalesStats.pending} 个售后请求待处理`,
      description: '请尽快处理避免客户等待',
      timestamp: now.toISOString(),
      metric: { label: '待处理', value: afterSalesStats.pending, trend: 'up' },
      action: { label: '立即处理', type: 'primary' }
    });
  }

  if (orderStats.confirmed > 0) {
    insights.push({
      id: 'pending_shipment',
      type: orderStats.confirmed >= 5 ? 'alert' : 'warning',
      priority: orderStats.confirmed >= 10 ? 'urgent' : 'medium',
      category: 'order',
      title: `${orderStats.confirmed} 个订单待发货`,
      description: '及时发货可提升客户体验',
      timestamp: now.toISOString(),
      metric: { label: '待发货', value: orderStats.confirmed, trend: 'neutral' },
      action: { label: '安排发货', type: 'primary' }
    });
  }

  const processingRate = afterSalesStats.total > 0 
    ? Math.round((afterSalesStats.completed / afterSalesStats.total) * 100) 
    : 100;

  insights.push({
    id: 'processing_rate',
    type: processingRate >= 60 ? 'success' : 'warning',
    priority: 'medium',
    category: 'service',
    title: `售后处理率 ${processingRate}%`,
    description: processingRate >= 60 ? '售后处理效率良好' : '建议加快处理速度',
    timestamp: now.toISOString(),
    progress: { current: processingRate, target: 100, label: '完成率' }
  });

  const deliveryRate = orderStats.total > 0 ? Math.round((orderStats.delivered / orderStats.total) * 100) : 100;

  insights.push({
    id: 'delivery_rate',
    type: deliveryRate >= 70 ? 'success' : 'opportunity',
    priority: 'medium',
    category: 'order',
    title: `订单履约率 ${deliveryRate}%`,
    description: `${orderStats.delivered} 个订单已送达，${orderStats.shipped} 个运输中`,
    timestamp: now.toISOString(),
    progress: { current: deliveryRate, target: 100, label: '履约率' }
  });

  return insights.slice(0, 6);
}

// ========================
// 意图识别 (回退模式)
// ========================

const INTENT_KEYWORDS: Record<string, string[]> = {
  'after_sales_pending': ['待处理', '待审核', '未处理', '需要处理'],
  'after_sales_list': ['售后', '退款', '换货', '退货', '投诉', '工单'],
  'orders_to_ship': ['待发货', '发货', '未发货'],
  'orders_list': ['订单', '交易', '购买'],
  'customers_list': ['客户', '用户', '买家'],
  'help': ['帮助', '怎么', '如何'],
};

function detectIntent(message: string | undefined, context?: GenUIRequest['context']): string {
  if (!message || typeof message !== 'string') return 'dashboard';
  const lower = message.toLowerCase();

  if (INTENT_KEYWORDS.after_sales_list.some(kw => lower.includes(kw))) {
    if (INTENT_KEYWORDS.after_sales_pending.some(kw => lower.includes(kw))) return 'after_sales_pending';
    return 'after_sales_list';
  }
  if (INTENT_KEYWORDS.after_sales_pending.some(kw => lower.includes(kw))) return 'after_sales_pending';
  if (INTENT_KEYWORDS.orders_list.some(kw => lower.includes(kw))) {
    if (INTENT_KEYWORDS.orders_to_ship.some(kw => lower.includes(kw))) return 'orders_to_ship';
    return 'orders_list';
  }
  if (INTENT_KEYWORDS.orders_to_ship.some(kw => lower.includes(kw))) return 'orders_to_ship';
  if (INTENT_KEYWORDS.customers_list.some(kw => lower.includes(kw))) return 'customers_list';
  if (INTENT_KEYWORDS.help.some(kw => lower.includes(kw))) return 'help';

  return 'dashboard';
}

// ========================
// 模板 UI 生成器 (回退模式)
// ========================

function generateDashboardUI(afterSalesStats: any, orderStats: any): UISchema {
  const urgentItems = [];
  if (afterSalesStats.pending > 0) {
    urgentItems.push({ type: 'alert', props: { type: 'warning', title: `${afterSalesStats.pending} 个售后待处理`, description: '请尽快处理' } });
  }
  if (orderStats.confirmed > 0) {
    urgentItems.push({ type: 'alert', props: { type: 'info', title: `${orderStats.confirmed} 个订单待发货`, description: '等待发货' } });
  }

  return {
    layout: 'vertical',
    gap: 'md',
    components: [
      ...(urgentItems.length > 0 ? urgentItems : [{ type: 'alert', props: { type: 'success', title: '客服状态良好', description: '暂无紧急事项' } }]),
      {
        type: 'stats_row',
        props: {
          items: [
            { label: '待处理售后', value: afterSalesStats.pending, color: afterSalesStats.pending > 0 ? 'warning' : 'muted' },
            { label: '处理中', value: afterSalesStats.processing, color: 'info' },
            { label: '已完成', value: afterSalesStats.completed, color: 'success' },
            { label: '待发货订单', value: orderStats.confirmed, color: orderStats.confirmed > 0 ? 'warning' : 'muted' },
          ],
        },
      },
    ],
  };
}

function generateAnswer(intent: string, afterSalesStats: any, orderStats: any): string {
  switch (intent) {
    case 'dashboard': return `客服概览：${afterSalesStats.pending} 个售后待处理，${orderStats.confirmed} 个订单待发货。`;
    case 'after_sales_pending': return `有 ${afterSalesStats.pending} 个售后请求待处理。`;
    case 'after_sales_list': return `共有 ${afterSalesStats.total} 个售后请求，${afterSalesStats.completed} 个已完成。`;
    case 'orders_to_ship': return `有 ${orderStats.confirmed} 个订单待发货。`;
    case 'orders_list': return `共有 ${orderStats.total} 个订单，${orderStats.delivered} 个已送达。`;
    case 'customers_list': return '可以查看客户列表和客户详情。';
    case 'help': return '这是客服管理帮助指南，您可以处理售后、查看订单、管理客户。';
    default: return '客服工作台已就绪，请告诉我您需要什么帮助。';
  }
}

// ========================
// Lovable AI Gateway 调用
// ========================

async function callLovableAI(
  userMessage: string,
  dataContext: string
): Promise<{ answer: string; ui_schema?: UISchema; suggested_actions?: string[] }> {
  const LOVABLE_AI_URL = _AI_CHAT_URL;
  const LOVABLE_AI_KEY = Deno.env.get('LOVABLE_API_KEY');

  if (!LOVABLE_AI_KEY) {
    console.log('[Service GenUI] LOVABLE_API_KEY not set, using fallback');
    return { answer: '当前未配置 AI，请联系管理员。' };
  }

  const systemPrompt = `${GENUI_COMPONENT_LIBRARY}

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

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

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

    if (!response.ok) {
      const errorText = await response.text();
      console.error('[Service GenUI] Lovable AI error:', errorText);
      throw new Error(`AI 调用失败: ${response.status}`);
    }

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

    if (!content) throw new Error('AI 返回内容为空');

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

    console.log('[Service GenUI] AI raw response:', jsonContent.substring(0, 500));

    const parsed = JSON.parse(jsonContent);
    return {
      answer: parsed.answer || '已为您生成界面',
      ui_schema: parsed.ui_schema,
      suggested_actions: parsed.suggested_actions,
    };
  } catch (error) {
    console.error('[Service GenUI] AI call failed:', error);
    throw error;
  }
}

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

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

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

    const body: GenUIRequest = await req.json();
    const { message, context } = body;

    console.log('[Service GenUI] Request:', { message, context });

    const data = await fetchServiceData(supabase, context);
    const { afterSalesStats, orderStats, afterSales, orders, users } = data;

    // 构建数据上下文
    const dataContext = `
售后统计:
- 待处理: ${afterSalesStats.pending} 个
- 处理中: ${afterSalesStats.processing} 个
- 已批准: ${afterSalesStats.approved} 个
- 已完成: ${afterSalesStats.completed} 个
- 已拒绝: ${afterSalesStats.rejected} 个
- 总计: ${afterSalesStats.total} 个
- 退款申请: ${afterSalesStats.refund} 个
- 换货申请: ${afterSalesStats.exchange} 个

订单统计:
- 待处理: ${orderStats.pending} 个
- 待发货: ${orderStats.confirmed} 个
- 已发货: ${orderStats.shipped} 个
- 已送达: ${orderStats.delivered} 个
- 已取消: ${orderStats.cancelled} 个
- 总计: ${orderStats.total} 个
- 总营收: ¥${orderStats.totalRevenue.toLocaleString()}

待处理售后样例(前5):
${afterSales.filter((a: any) => a.status === 'pending').slice(0, 5).map((a: any) => `- ${a.type}: ${a.reason || '无原因'}`).join('\n') || '无'}

待发货订单样例(前5):
${orders.filter((o: any) => o.status === 'confirmed').slice(0, 5).map((o: any) => `- 订单 ¥${o.total_amount}`).join('\n') || '无'}
`;

    let uiSchema: UISchema;
    let answer: string;
    let suggested_actions: string[] = ['待处理售后', '待发货订单', '客户列表', '工作概览'];

    const useDynamicAI = Deno.env.get('LOVABLE_API_KEY') && Deno.env.get('USE_DYNAMIC_GENUI') !== 'false';

    if (useDynamicAI && message) {
      try {
        console.log('[Service GenUI] Using Lovable AI for dynamic schema generation');
        const aiResult = await callLovableAI(message, dataContext);
        
        if (aiResult.ui_schema) {
          uiSchema = aiResult.ui_schema;
          answer = aiResult.answer;
          if (aiResult.suggested_actions) suggested_actions = aiResult.suggested_actions;
          console.log('[Service GenUI] AI generated schema successfully');
        } else {
          throw new Error('AI 未返回有效 schema');
        }
      } catch (aiError) {
        console.warn('[Service GenUI] AI fallback to template:', aiError);
        const intent = detectIntent(message, context);
        uiSchema = generateDashboardUI(afterSalesStats, orderStats);
        answer = generateAnswer(intent, afterSalesStats, orderStats);
      }
    } else {
      const intent = detectIntent(message, context);
      console.log('[Service GenUI] Using template mode, intent:', intent);
      uiSchema = generateDashboardUI(afterSalesStats, orderStats);
      answer = generateAnswer(intent, afterSalesStats, orderStats);
    }

    const response: GenUIResponse = {
      answer,
      ui_schema: uiSchema,
      insights: data.insights,
      suggested_actions,
    };

    console.log('[Service GenUI] Response generated successfully');

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

  } catch (error) {
    console.error('[Service GenUI] Error:', error);
    return new Response(JSON.stringify({
      success: false,
      error: (error instanceof Error ? error.message : 'Unknown error'),
      answer: '抱歉，处理请求时出现错误，请稍后重试。',
    }), {
      status: 500,
      headers: { ...corsHeaders, 'Content-Type': 'application/json' },
    });
  }
});
