/**
 * 店长版块 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 ManagerInsight {
  id: string;
  type: 'warning' | 'success' | 'opportunity' | 'alert' | 'info';
  priority: 'low' | 'medium' | 'high' | 'urgent';
  title: string;
  description: string;
  timestamp: string;
  metric?: { label: string; value: string | number; trend?: 'up' | 'down' | 'neutral' };
  action?: { label: string; type?: 'primary' | 'secondary' };
  agent?: string;
}

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

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

const GENUI_COMPONENT_LIBRARY = `
你是店铺总管 AI 助手（小管），负责根据用户查询动态生成 UI Schema。你需要全局视角看待店铺运营。

## 可用组件库

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

### stats_row - 统计指标行
{ "type": "stats_row", "props": { "items": [{ "label": "标签", "value": "值", "color": "success" }] } }

### data_table - 数据表格
{ 
  "type": "data_table", 
  "props": { 
    "title": "表格标题",
    "columns": [{ "key": "name", "label": "姓名" }, { "key": "phone", "label": "电话" }],
    "rows": [{ "name": "张三", "phone": "138****1234" }]
  } 
}

### chart - 图表
{ "type": "chart", "props": { "title": "图表标题", "type": "pie", "data": [{ "label": "A", "value": 100 }] } }

### alert - 警告/提示
{ "type": "alert", "props": { "type": "warning", "title": "标题", "description": "描述" } }

### insight_card - 洞察卡片
{ "type": "insight_card", "props": { "type": "info", "title": "标题", "description": "描述" } }

### progress_bar - 进度条
{ "type": "progress_bar", "props": { "label": "进度", "current": 50, "target": 100 } }

## 输出格式（严格遵循）

{
  "answer": "回复文字",
  "ui_schema": {
    "layout": "vertical",
    "gap": "md",
    "components": [
      { "type": "组件类型", "props": { ... } }
    ]
  },
  "suggested_actions": ["操作1", "操作2"]
}

## 规则
1. 每个组件必须有 type 和 props 两个字段
2. title、columns、rows 等都必须放在 props 内部
3. 使用数据上下文中的真实数据填充表格行
4. 如用户查询客户/用户列表，直接用提供的用户数据生成 data_table
5. 保持界面简洁，最多 6 个组件
`;

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

async function fetchManagerData(supabase: any) {
  console.log('[Manager GenUI] Fetching manager data...');
  
  const now = new Date();
  const today = now.toISOString().split('T')[0];
  const monthStart = new Date(now.getFullYear(), now.getMonth(), 1).toISOString();
  const weekStart = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000).toISOString();
  const sixtyDaysAgo = new Date(now.getTime() - 60 * 24 * 60 * 60 * 1000).toISOString();

  const [ordersResult, productsResult, usersResult, campaignsResult, afterSalesResult, lowStockResult, hotProductsResult, userProfilesResult] = await Promise.all([
    supabase.from('orders').select('id, total_amount, status, created_at').gte('created_at', sixtyDaysAgo).order('created_at', { ascending: false }).limit(500),
    supabase.from('products').select('id, name, category, stock_quantity, monthly_sales, is_active', { count: 'exact' }).eq('is_active', true),
    supabase.from('profiles').select('id, created_at', { count: 'exact' }),
    supabase.from('marketing_campaigns').select('id, name, status, type').in('status', ['active', 'pending']),
    supabase.from('after_sales_requests').select('id, type, status, created_at').gte('created_at', weekStart),
    supabase.from('products').select('id, name, stock_quantity').eq('is_active', true).lt('stock_quantity', 10).order('stock_quantity', { ascending: true }).limit(10),
    supabase.from('products').select('id, name, monthly_sales, price').eq('is_active', true).eq('is_hot', true).order('monthly_sales', { ascending: false }).limit(5),
    // 获取完整用户信息列表
    supabase.from('profiles').select('id, user_id, display_name, phone, role, email_verified, last_login, created_at').order('created_at', { ascending: false }).limit(100)
  ]);

  const orders = ordersResult.data || [];
  const products = productsResult.data || [];
  const users = usersResult.data || [];
  const campaigns = campaignsResult.data || [];
  const afterSales = afterSalesResult.data || [];
  const lowStock = lowStockResult.data || [];
  const hotProducts = hotProductsResult.data || [];
  const userProfiles = userProfilesResult.data || [];

  const thisMonthOrders = orders.filter((o: any) => new Date(o.created_at) >= new Date(monthStart));
  const thisMonthRevenue = thisMonthOrders.filter((o: any) => o.status !== 'cancelled').reduce((sum: number, o: any) => sum + (o.total_amount || 0), 0);

  const lastMonthStart = new Date(now.getFullYear(), now.getMonth() - 1, 1);
  const lastMonthEnd = new Date(now.getFullYear(), now.getMonth(), 0);
  const lastMonthOrders = orders.filter((o: any) => {
    const date = new Date(o.created_at);
    return date >= lastMonthStart && date <= lastMonthEnd;
  });
  const lastMonthRevenue = lastMonthOrders.filter((o: any) => o.status !== 'cancelled').reduce((sum: number, o: any) => sum + (o.total_amount || 0), 0);

  const todayOrders = orders.filter((o: any) => o.created_at.startsWith(today));
  const todayRevenue = todayOrders.reduce((sum: number, o: any) => sum + (o.total_amount || 0), 0);

  const pendingOrders = orders.filter((o: any) => o.status === 'pending').length;
  const pendingAfterSales = afterSales.filter((a: any) => a.status === 'pending').length;
  const activeCampaigns = campaigns.filter((c: any) => c.status === 'active').length;
  const pendingCampaigns = campaigns.filter((c: any) => c.status === 'pending').length;
  const weekNewUsers = users.filter((u: any) => new Date(u.created_at) >= new Date(weekStart)).length;
  const growthRate = lastMonthRevenue > 0 ? ((thisMonthRevenue - lastMonthRevenue) / lastMonthRevenue * 100) : 0;

  // 订单状态分布
  const orderStatusMap: Record<string, number> = {};
  orders.forEach((o: any) => { orderStatusMap[o.status] = (orderStatusMap[o.status] || 0) + 1; });

  console.log('[Manager GenUI] Data fetched:', { ordersCount: orders.length, productsCount: products.length, userProfilesCount: userProfiles.length });

  const insights = generateManagerInsights({
    thisMonthRevenue, lastMonthRevenue, todayRevenue, growthRate,
    totalProducts: productsResult.count || products.length,
    totalUsers: usersResult.count || users.length,
    pendingOrders, pendingAfterSales, activeCampaigns, pendingCampaigns,
    lowStockCount: lowStock.length, weekNewUsers
  }, lowStock, hotProducts);

  return {
    orders,
    products,
    lowStock,
    hotProducts,
    userProfiles,  // 新增：用户资料列表
    stats: {
      thisMonthRevenue, lastMonthRevenue, todayRevenue, growthRate,
      totalProducts: productsResult.count || products.length,
      totalUsers: usersResult.count || users.length,
      totalOrders: orders.length,
      pendingOrders, pendingAfterSales, activeCampaigns, pendingCampaigns,
      lowStockCount: lowStock.length, weekNewUsers
    },
    orderStatusData: Object.entries(orderStatusMap).map(([status, count]) => ({
      label: translateStatus(status),
      value: count
    })),
    insights,
  };
}

function translateStatus(status: string): string {
  const map: Record<string, string> = {
    'pending': '待处理', 'paid': '已支付', 'confirmed': '已确认',
    'shipped': '已发货', 'delivered': '已送达', 'completed': '已完成', 'cancelled': '已取消'
  };
  return map[status] || status;
}

function generateManagerInsights(stats: any, lowStock: any[], hotProducts: any[]): ManagerInsight[] {
  const insights: ManagerInsight[] = [];
  const now = new Date();

  // 营收表现
  insights.push({
    id: 'revenue_performance',
    type: stats.growthRate >= 0 ? 'success' : 'warning',
    priority: 'high',
    title: `本月营收 ¥${stats.thisMonthRevenue.toLocaleString()}`,
    description: `环比${stats.growthRate >= 0 ? '增长' : '下降'} ${Math.abs(stats.growthRate).toFixed(1)}%`,
    timestamp: now.toISOString(),
    metric: { label: '月营收', value: `¥${stats.thisMonthRevenue.toLocaleString()}`, trend: stats.growthRate >= 0 ? 'up' : 'down' }
  });

  if (stats.lowStockCount > 0) {
    insights.push({
      id: 'low_stock_warning',
      type: 'warning',
      priority: stats.lowStockCount >= 5 ? 'high' : 'medium',
      title: `${stats.lowStockCount} 款商品库存不足`,
      description: '库存低于10件，需要及时补货',
      timestamp: now.toISOString(),
      metric: { label: '低库存', value: stats.lowStockCount, trend: 'down' },
      action: { label: '查看详情', type: 'primary' },
      agent: 'product'
    });
  }

  if (stats.pendingAfterSales > 0) {
    insights.push({
      id: 'pending_aftersales',
      type: 'alert',
      priority: stats.pendingAfterSales >= 5 ? 'urgent' : 'high',
      title: `${stats.pendingAfterSales} 个售后待处理`,
      description: '请客服部门尽快处理',
      timestamp: now.toISOString(),
      metric: { label: '待处理', value: stats.pendingAfterSales, trend: 'up' },
      action: { label: '立即处理', type: 'primary' },
      agent: 'service'
    });
  }

  if (stats.pendingCampaigns > 0) {
    insights.push({
      id: 'pending_campaigns',
      type: 'info',
      priority: 'medium',
      title: `${stats.pendingCampaigns} 个活动待审批`,
      description: '营销活动等待审批',
      timestamp: now.toISOString(),
      metric: { label: '待审批', value: stats.pendingCampaigns, trend: 'neutral' },
      action: { label: '审批', type: 'secondary' },
      agent: 'marketing'
    });
  }

  insights.push({
    id: 'user_growth',
    type: 'success',
    priority: 'low',
    title: `本周新增 ${stats.weekNewUsers} 位用户`,
    description: `总用户 ${stats.totalUsers} 人`,
    timestamp: now.toISOString(),
    metric: { label: '新增用户', value: stats.weekNewUsers, trend: 'up' }
  });

  return insights.slice(0, 6);
}

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

function detectIntent(message: string | undefined, view?: string): string {
  if (view && view !== 'dashboard') return view;
  if (!message || typeof message !== 'string') return 'dashboard';
  
  const lowerMsg = message.toLowerCase();
  
  if (lowerMsg.includes('商品') || lowerMsg.includes('库存') || lowerMsg.includes('产品')) return 'products';
  if (lowerMsg.includes('订单') || lowerMsg.includes('发货')) return 'orders';
  if (lowerMsg.includes('营销') || lowerMsg.includes('活动') || lowerMsg.includes('促销')) return 'marketing';
  if (lowerMsg.includes('售后') || lowerMsg.includes('退款')) return 'aftersales';
  if (lowerMsg.includes('用户') || lowerMsg.includes('会员')) return 'users';
  if (lowerMsg.includes('帮助') || lowerMsg.includes('怎么')) return 'help';
  
  return 'dashboard';
}

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

function generateDashboardUI(stats: any, orderStatusData: any[]): UISchema {
  return {
    layout: 'vertical',
    gap: 'md',
    components: [
      {
        type: 'stats_row',
        props: {
          items: [
            { label: '本月营收', value: `¥${stats.thisMonthRevenue.toLocaleString()}`, color: 'success' },
            { label: '今日营收', value: `¥${stats.todayRevenue.toLocaleString()}`, color: 'default' },
            { label: '待处理订单', value: `${stats.pendingOrders}单`, color: stats.pendingOrders > 0 ? 'warning' : 'default' },
            { label: '库存预警', value: `${stats.lowStockCount}件`, color: stats.lowStockCount > 0 ? 'error' : 'default' }
          ],
        }
      },
      {
        type: 'container',
        props: {
          layout: 'horizontal',
          gap: 'md',
          children: [
            { type: 'chart', props: { title: '订单状态分布', type: 'pie', data: orderStatusData, height: 200 } }
          ]
        }
      }
    ],
  };
}

function generateAnswer(intent: string, stats: any): string {
  switch (intent) {
    case 'dashboard': return `店铺概览：本月营收 ¥${stats.thisMonthRevenue.toLocaleString()}，${stats.pendingOrders} 个待处理订单，${stats.lowStockCount} 件商品库存预警。`;
    case 'products': return `共有 ${stats.totalProducts} 款在售商品，${stats.lowStockCount} 款库存不足。`;
    case 'orders': return `共有 ${stats.totalOrders} 个订单，${stats.pendingOrders} 个待处理。`;
    case 'marketing': return `有 ${stats.activeCampaigns} 个进行中活动，${stats.pendingCampaigns} 个待审批。`;
    case 'aftersales': return `有 ${stats.pendingAfterSales} 个售后待处理。`;
    case 'users': return `共有 ${stats.totalUsers} 位用户，本周新增 ${stats.weekNewUsers} 位。`;
    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('[Manager 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("manager_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('[Manager 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('[Manager 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('[Manager 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('[Manager GenUI] Request:', { message, context });

    const data = await fetchManagerData(supabase);
    const { stats, orderStatusData, lowStock, hotProducts, orders, userProfiles } = data;

    // 构建数据上下文
    const dataContext = `
店铺经营概览:
- 本月营收: ¥${stats.thisMonthRevenue.toLocaleString()}
- 上月营收: ¥${stats.lastMonthRevenue.toLocaleString()}
- 环比增长: ${stats.growthRate.toFixed(1)}%
- 今日营收: ¥${stats.todayRevenue.toLocaleString()}
- 总订单数: ${stats.totalOrders} 个
- 待处理订单: ${stats.pendingOrders} 个

商品状态:
- 在售商品: ${stats.totalProducts} 款
- 库存预警: ${stats.lowStockCount} 款

客服状态:
- 待处理售后: ${stats.pendingAfterSales} 个

营销状态:
- 进行中活动: ${stats.activeCampaigns} 个
- 待审批活动: ${stats.pendingCampaigns} 个

用户增长:
- 总用户数: ${stats.totalUsers} 人
- 本周新增: ${stats.weekNewUsers} 人

用户/客户列表(真实数据):
${userProfiles.map((u: any) => `- ID: ${u.user_id?.slice(0, 8) || u.id?.slice(0, 8)}..., 姓名: ${u.display_name || '未设置'}, 手机: ${u.phone || '未填写'}, 角色: ${u.role === 'admin' ? '管理员' : '普通用户'}, 注册时间: ${u.created_at?.split('T')[0] || '未知'}`).join('\n') || '暂无用户'}

低库存商品样例(前5):
${lowStock.slice(0, 5).map((p: any) => `- ${p.name}: 库存${p.stock_quantity}件`).join('\n') || '无'}

热销商品样例(前5):
${hotProducts.slice(0, 5).map((p: any) => `- ${p.name}: 月销${p.monthly_sales}件`).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('[Manager 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('[Manager GenUI] AI generated schema successfully');
        } else {
          throw new Error('AI 未返回有效 schema');
        }
      } catch (aiError) {
        console.warn('[Manager GenUI] AI fallback to template:', aiError);
        const intent = detectIntent(message, context?.current_view);
        uiSchema = generateDashboardUI(stats, orderStatusData);
        answer = generateAnswer(intent, stats);
      }
    } else {
      const intent = detectIntent(message, context?.current_view);
      console.log('[Manager GenUI] Using template mode, intent:', intent);
      uiSchema = generateDashboardUI(stats, orderStatusData);
      answer = generateAnswer(intent, stats);
    }

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

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

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

  } catch (error) {
    console.error('[Manager 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' },
    });
  }
});
