/**
 * 商品版块 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 ProductInsight {
  id: string;
  type: 'warning' | 'success' | 'opportunity' | 'alert' | 'suggestion' | 'info';
  priority: 'low' | 'medium' | 'high' | 'urgent';
  category: 'inventory' | 'sales' | 'pricing' | 'category';
  title: string;
  description: string;
  confidence?: number;
  timestamp: string;
  metric?: { label: string; value: string | number; unit?: string; trend?: 'up' | 'down' | 'neutral'; trendValue?: string };
  progress?: { current: number; target: number; label?: string };
  action?: { label: string; type?: 'primary' | 'secondary' };
}

interface GenUIResponse {
  answer: string;
  ui_schema?: UISchema;
  insights?: ProductInsight[];
  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' }] }

### data_table - 数据表格
用于展示列表数据
props: { 
  title?: string,
  columns: [{ key: string, label: string, 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', title: string, description: string, metric?: { label: string, value: string } }

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

### text_block - 文本块
props: { variant: 'heading'|'body'|'caption', content: string }

## 输出格式

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

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

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

async function fetchProductData(supabase: any, context?: GenUIRequest['context']) {
  console.log('[Product GenUI] Fetching product data...', context);

  const [productsRes, categoriesRes, brandsRes, ordersRes] = await Promise.all([
    // 商品数据
    supabase
      .from('products')
      .select('*')
      .order('created_at', { ascending: false })
      .limit(200),
    
    // 分类数据
    supabase
      .from('categories')
      .select('*')
      .order('display_order', { ascending: true }),
    
    // 品牌数据
    supabase
      .from('brands')
      .select('*')
      .order('display_order', { ascending: true }),
    
    // 近期订单（计算销售数据）
    supabase
      .from('orders')
      .select('id, total_amount, status, created_at')
      .gte('created_at', new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString())
      .order('created_at', { ascending: false })
      .limit(500),
  ]);

  const products = productsRes.data || [];
  const categories = categoriesRes.data || [];
  const brands = brandsRes.data || [];
  const orders = ordersRes.data || [];

  // 计算商品统计
  const activeProducts = products.filter((p: any) => p.is_active);
  const productStats = {
    total: products.length,
    active: activeProducts.length,
    inactive: products.length - activeProducts.length,
    lowStock: activeProducts.filter((p: any) => p.stock_quantity <= 10).length,
    outOfStock: activeProducts.filter((p: any) => p.stock_quantity === 0).length,
    slowMoving: activeProducts.filter((p: any) => (p.monthly_sales || 0) < 5 && p.stock_quantity > 20).length,
    hotProducts: activeProducts.filter((p: any) => p.is_hot).length,
    recommended: activeProducts.filter((p: any) => p.is_recommended).length,
    totalStock: activeProducts.reduce((sum: number, p: any) => sum + (p.stock_quantity || 0), 0),
    avgPrice: activeProducts.length > 0 
      ? Math.round(activeProducts.reduce((sum: number, p: any) => sum + (p.price || 0), 0) / activeProducts.length)
      : 0,
  };

  // 分类统计
  const categoryStats = {
    total: categories.length,
    active: categories.filter((c: any) => c.is_active).length,
    topLevel: categories.filter((c: any) => !c.parent_id).length,
  };

  // 品牌统计
  const brandStats = {
    total: brands.length,
    active: brands.filter((b: any) => b.is_active).length,
  };

  // 销售统计
  const sevenDaysAgo = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000);
  const recentOrders = orders.filter((o: any) => new Date(o.created_at) >= sevenDaysAgo);
  const orderStats = {
    weeklyOrders: recentOrders.length,
    weeklyRevenue: recentOrders.reduce((sum: number, o: any) => sum + (o.total_amount || 0), 0),
    monthlyOrders: orders.length,
    monthlyRevenue: orders.reduce((sum: number, o: any) => sum + (o.total_amount || 0), 0),
  };

  console.log('[Product GenUI] Data fetched:', {
    productsCount: products.length,
    categoriesCount: categories.length,
    brandsCount: brands.length,
  });

  // 生成洞察
  const insights = generateProductInsights(productStats, categoryStats, brandStats, orderStats, products);

  return {
    products,
    categories,
    brands,
    productStats,
    categoryStats,
    brandStats,
    orderStats,
    insights,
  };
}

// 生成商品相关洞察
function generateProductInsights(
  productStats: any,
  categoryStats: any,
  brandStats: any,
  orderStats: any,
  products: any[]
): ProductInsight[] {
  const insights: ProductInsight[] = [];
  const now = new Date();

  // 1. 库存不足预警
  if (productStats.lowStock > 0) {
    insights.push({
      id: 'low_stock_alert',
      type: productStats.lowStock >= 5 ? 'alert' : 'warning',
      priority: productStats.lowStock >= 10 ? 'urgent' : productStats.lowStock >= 5 ? 'high' : 'medium',
      category: 'inventory',
      title: `${productStats.lowStock} 款商品库存不足`,
      description: `库存低于10件，需要及时补货以避免断货`,
      confidence: 100,
      timestamp: now.toISOString(),
      metric: { label: '低库存', value: productStats.lowStock, trend: 'down' },
      action: { label: '立即补货', type: 'primary' }
    });
  }

  // 2. 缺货商品
  if (productStats.outOfStock > 0) {
    insights.push({
      id: 'out_of_stock',
      type: 'alert',
      priority: 'urgent',
      category: 'inventory',
      title: `${productStats.outOfStock} 款商品已断货`,
      description: '库存为0，无法销售，请尽快补货',
      confidence: 100,
      timestamp: now.toISOString(),
      metric: { label: '断货', value: productStats.outOfStock, trend: 'down' },
      action: { label: '查看详情', type: 'primary' }
    });
  }

  // 3. 滞销商品提醒
  if (productStats.slowMoving > 0) {
    insights.push({
      id: 'slow_moving',
      type: 'opportunity',
      priority: 'medium',
      category: 'sales',
      title: `${productStats.slowMoving} 款商品滞销`,
      description: '月销量低于5件但库存超过20件，建议促销或调价',
      confidence: 90,
      timestamp: now.toISOString(),
      metric: { label: '滞销商品', value: productStats.slowMoving, trend: 'neutral' },
      action: { label: '优化建议', type: 'secondary' }
    });
  }

  // 4. 库存周转率
  const stockTurnover = orderStats.monthlyRevenue > 0 && productStats.totalStock > 0
    ? (orderStats.monthlyRevenue / (productStats.totalStock * productStats.avgPrice) * 100).toFixed(1)
    : 0;
  
  insights.push({
    id: 'stock_turnover',
    type: Number(stockTurnover) >= 50 ? 'success' : 'opportunity',
    priority: 'medium',
    category: 'inventory',
    title: `库存周转率 ${stockTurnover}%`,
    description: `本月库存周转情况${Number(stockTurnover) >= 50 ? '良好' : '偏低，可优化库存结构'}`,
    confidence: 85,
    timestamp: now.toISOString(),
    progress: { current: Math.min(Number(stockTurnover), 100), target: 100, label: '周转率' }
  });

  // 5. 商品活跃度
  const activeRate = productStats.total > 0 
    ? Math.round((productStats.active / productStats.total) * 100) 
    : 100;
  
  if (activeRate < 80) {
    insights.push({
      id: 'low_active_rate',
      type: 'warning',
      priority: 'low',
      category: 'inventory',
      title: `商品活跃率 ${activeRate}%`,
      description: `${productStats.inactive} 款商品已下架，可考虑清理或重新上架`,
      confidence: 100,
      timestamp: now.toISOString(),
      progress: { current: activeRate, target: 100, label: '活跃率' }
    });
  }

  // 6. 周销售表现
  const weeklyGrowth = orderStats.weeklyRevenue > 0 && orderStats.monthlyRevenue > 0
    ? Math.round((orderStats.weeklyRevenue / (orderStats.monthlyRevenue / 4)) * 100 - 100)
    : 0;

  insights.push({
    id: 'weekly_sales',
    type: weeklyGrowth >= 0 ? 'success' : 'warning',
    priority: 'medium',
    category: 'sales',
    title: `本周销售 ¥${orderStats.weeklyRevenue.toLocaleString()}`,
    description: `共 ${orderStats.weeklyOrders} 笔订单，${weeklyGrowth >= 0 ? '超过' : '低于'}周均 ${Math.abs(weeklyGrowth)}%`,
    confidence: 95,
    timestamp: now.toISOString(),
    metric: {
      label: '周销售',
      value: `¥${orderStats.weeklyRevenue.toLocaleString()}`,
      trend: weeklyGrowth >= 0 ? 'up' : 'down',
      trendValue: `${weeklyGrowth >= 0 ? '+' : ''}${weeklyGrowth}%`
    },
  });

  return insights.slice(0, 6);
}

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

const INTENT_KEYWORDS = {
  dashboard: ['概览', '工作台', '仪表盘', '总览', '首页', '看看', '驾驶舱'],
  products_list: ['商品', '产品', '货品', '全部商品'],
  products_low_stock: ['低库存', '库存不足', '缺货', '断货', '补货'],
  products_slow_moving: ['滞销', '卖不动', '销量低'],
  products_hot: ['热销', '爆款', '畅销'],
  products_new: ['新品', '新上架', '最新'],
  categories_list: ['分类', '类目', '品类'],
  brands_list: ['品牌', '厂商', '供应商'],
  analytics: ['数据', '分析', '统计', '报表', '销量'],
  help: ['帮助', '怎么', '如何', '教我', '指南'],
};

function detectIntent(message: string | undefined, context?: GenUIRequest['context']): string {
  // 如果message为空或undefined，默认返回dashboard
  if (!message || typeof message !== 'string') {
    return 'dashboard';
  }
  const lower = message.toLowerCase();

  // 商品相关
  if (INTENT_KEYWORDS.products_list.some(kw => lower.includes(kw))) {
    if (INTENT_KEYWORDS.products_low_stock.some(kw => lower.includes(kw))) {
      return 'products_low_stock';
    }
    if (INTENT_KEYWORDS.products_slow_moving.some(kw => lower.includes(kw))) {
      return 'products_slow_moving';
    }
    if (INTENT_KEYWORDS.products_hot.some(kw => lower.includes(kw))) {
      return 'products_hot';
    }
    if (INTENT_KEYWORDS.products_new.some(kw => lower.includes(kw))) {
      return 'products_new';
    }
    return 'products_list';
  }

  // 单独的库存关键词
  if (INTENT_KEYWORDS.products_low_stock.some(kw => lower.includes(kw))) {
    return 'products_low_stock';
  }
  if (INTENT_KEYWORDS.products_slow_moving.some(kw => lower.includes(kw))) {
    return 'products_slow_moving';
  }

  // 分类相关
  if (INTENT_KEYWORDS.categories_list.some(kw => lower.includes(kw))) {
    return 'categories_list';
  }

  // 品牌相关
  if (INTENT_KEYWORDS.brands_list.some(kw => lower.includes(kw))) {
    return 'brands_list';
  }

  // 数据分析
  if (INTENT_KEYWORDS.analytics.some(kw => lower.includes(kw))) {
    return 'analytics';
  }

  // 帮助
  if (INTENT_KEYWORDS.help.some(kw => lower.includes(kw))) {
    return 'help';
  }

  // 概览
  if (INTENT_KEYWORDS.dashboard.some(kw => lower.includes(kw))) {
    return 'dashboard';
  }

  return 'dashboard';
}

// ========================
// UI Schema 生成器
// ========================

function generateDashboardUI(data: any): UISchema {
  const { productStats, categoryStats, brandStats, orderStats } = data;
  
  const urgentItems = [];
  if (productStats.outOfStock > 0) {
    urgentItems.push({
      type: 'alert',
      props: {
        type: 'error',
        title: `${productStats.outOfStock} 款商品已断货`,
        description: '请尽快补货',
        closable: false,
      },
    });
  }
  if (productStats.lowStock > 0) {
    urgentItems.push({
      type: 'alert',
      props: {
        type: 'warning',
        title: `${productStats.lowStock} 款商品库存不足`,
        description: '库存低于10件，建议补货',
        closable: false,
      },
    });
  }

  return {
    layout: 'vertical',
    gap: 'md',
    components: [
      // 紧急事项
      ...(urgentItems.length > 0 ? urgentItems : [{
        type: 'alert',
        props: {
          type: 'success',
          title: '商品状态良好',
          description: '暂无紧急事项需要处理',
          closable: false,
        },
      }]),
      // 核心指标
      {
        type: 'stats_row',
        props: {
          items: [
            { label: '上架商品', value: productStats.active, color: 'info' },
            { label: '低库存', value: productStats.lowStock, color: 'warning' },
            { label: '滞销商品', value: productStats.slowMoving, color: 'muted' },
            { label: '本周销售', value: `¥${orderStats.weeklyRevenue.toLocaleString()}`, color: 'success' },
          ],
        },
      },
      // 双列布局
      {
        type: 'container',
        props: {
          layout: 'grid',
          columns: 2,
          gap: 'md',
          children: [
            {
              type: 'chart',
              props: {
                title: '库存状态分布',
                type: 'pie',
                data: [
                  { label: '正常', value: productStats.active - productStats.lowStock - productStats.outOfStock },
                  { label: '低库存', value: productStats.lowStock },
                  { label: '断货', value: productStats.outOfStock },
                ],
                height: 200,
              },
            },
            {
              type: 'chart',
              props: {
                title: '商品状态',
                type: 'bar',
                data: [
                  { label: '上架', value: productStats.active },
                  { label: '下架', value: productStats.inactive },
                  { label: '热销', value: productStats.hotProducts },
                  { label: '推荐', value: productStats.recommended },
                ],
                height: 200,
              },
            },
          ],
        },
      },
    ],
  };
}

function generateProductsListUI(data: any, filter?: string): UISchema {
  let products = data.products || [];
  let title = '商品列表';
  
  switch (filter) {
    case 'low_stock':
      products = products.filter((p: any) => p.is_active && p.stock_quantity <= 10);
      title = '低库存商品';
      break;
    case 'slow_moving':
      products = products.filter((p: any) => p.is_active && (p.monthly_sales || 0) < 5 && p.stock_quantity > 20);
      title = '滞销商品';
      break;
    case 'hot':
      products = products.filter((p: any) => p.is_hot);
      title = '热销商品';
      break;
    case 'new':
      products = products.slice(0, 20);
      title = '新上架商品';
      break;
  }

  const tableData = products.slice(0, 20).map((p: any) => ({
    id: p.id,
    name: p.name,
    price: `¥${p.price}`,
    stock: p.stock_quantity,
    sales: p.monthly_sales || 0,
    status: p.is_active ? '上架' : '下架',
  }));

  return {
    layout: 'vertical',
    gap: 'md',
    components: [
      {
        type: 'text_block',
        props: {
          variant: 'heading',
          content: title,
        },
      },
      {
        type: 'stats_row',
        props: {
          items: [
            { label: '共计', value: products.length, color: 'info' },
          ],
        },
      },
      {
        type: 'data_table',
        props: {
          columns: [
            { key: 'name', label: '商品名称' },
            { key: 'price', label: '价格' },
            { key: 'stock', label: '库存' },
            { key: 'sales', label: '月销量' },
            { key: 'status', label: '状态' },
          ],
          data: tableData,
          pageSize: 10,
        },
      },
    ],
  };
}

function generateCategoriesListUI(data: any): UISchema {
  const categories = data.categories || [];
  const tableData = categories.slice(0, 20).map((c: any) => ({
    id: c.id,
    name: c.name,
    description: c.description || '-',
    order: c.display_order || 0,
    status: c.is_active ? '启用' : '禁用',
  }));

  return {
    layout: 'vertical',
    gap: 'md',
    components: [
      {
        type: 'text_block',
        props: {
          variant: 'heading',
          content: '商品分类',
        },
      },
      {
        type: 'stats_row',
        props: {
          items: [
            { label: '总分类数', value: data.categoryStats.total, color: 'info' },
            { label: '启用', value: data.categoryStats.active, color: 'success' },
            { label: '顶级分类', value: data.categoryStats.topLevel, color: 'muted' },
          ],
        },
      },
      {
        type: 'data_table',
        props: {
          columns: [
            { key: 'name', label: '分类名称' },
            { key: 'description', label: '描述' },
            { key: 'order', label: '排序' },
            { key: 'status', label: '状态' },
          ],
          data: tableData,
          pageSize: 10,
        },
      },
    ],
  };
}

function generateBrandsListUI(data: any): UISchema {
  const brands = data.brands || [];
  const tableData = brands.slice(0, 20).map((b: any) => ({
    id: b.id,
    name: b.name,
    description: b.description || '-',
    order: b.display_order || 0,
    status: b.is_active ? '启用' : '禁用',
  }));

  return {
    layout: 'vertical',
    gap: 'md',
    components: [
      {
        type: 'text_block',
        props: {
          variant: 'heading',
          content: '品牌管理',
        },
      },
      {
        type: 'stats_row',
        props: {
          items: [
            { label: '总品牌数', value: data.brandStats.total, color: 'info' },
            { label: '启用', value: data.brandStats.active, color: 'success' },
          ],
        },
      },
      {
        type: 'data_table',
        props: {
          columns: [
            { key: 'name', label: '品牌名称' },
            { key: 'description', label: '描述' },
            { key: 'order', label: '排序' },
            { key: 'status', label: '状态' },
          ],
          data: tableData,
          pageSize: 10,
        },
      },
    ],
  };
}

function generateAnalyticsUI(data: any): UISchema {
  const { productStats, orderStats } = data;
  
  return {
    layout: 'vertical',
    gap: 'md',
    components: [
      {
        type: 'text_block',
        props: {
          variant: 'heading',
          content: '商品数据分析',
        },
      },
      {
        type: 'stats_row',
        props: {
          items: [
            { label: '上架商品', value: productStats.active, color: 'info' },
            { label: '本周销售', value: `¥${orderStats.weeklyRevenue.toLocaleString()}`, color: 'success' },
            { label: '本月销售', value: `¥${orderStats.monthlyRevenue.toLocaleString()}`, color: 'success' },
            { label: '总库存', value: productStats.totalStock, color: 'muted' },
          ],
        },
      },
      {
        type: 'container',
        props: {
          layout: 'grid',
          columns: 2,
          gap: 'md',
          children: [
            {
              type: 'chart',
              props: {
                title: '库存结构分析',
                type: 'pie',
                data: [
                  { label: '正常库存', value: productStats.active - productStats.lowStock },
                  { label: '低库存', value: productStats.lowStock },
                  { label: '滞销', value: productStats.slowMoving },
                ],
                height: 200,
              },
            },
            {
              type: 'chart',
              props: {
                title: '商品标签分布',
                type: 'bar',
                data: [
                  { label: '热销', value: productStats.hotProducts },
                  { label: '推荐', value: productStats.recommended },
                  { label: '下架', value: productStats.inactive },
                ],
                height: 200,
              },
            },
          ],
        },
      },
    ],
  };
}

function generateHelpUI(): UISchema {
  return {
    layout: 'vertical',
    gap: 'md',
    components: [
      {
        type: 'text_block',
        props: {
          variant: 'heading',
          content: '商品管理指南',
        },
      },
      {
        type: 'text_block',
        props: {
          variant: 'body',
          content: `
## 常用操作

### 商品管理
- 说"查看商品"可以查看所有商品
- 说"低库存商品"查看需要补货的商品
- 说"滞销商品"查看销量低的商品
- 说"热销商品"查看爆款商品

### 分类管理
- 说"查看分类"查看所有分类
- 可以新增、编辑、删除分类

### 品牌管理
- 说"查看品牌"查看所有品牌
- 可以管理品牌信息

### 数据分析
- 说"商品数据"或"销售分析"查看统计报表
          `,
        },
      },
    ],
  };
}

// ========================
// 应答生成
// ========================

function generateAnswer(intent: string, data: any): string {
  const { productStats, categoryStats, brandStats, orderStats } = data;
  
  switch (intent) {
    case 'dashboard':
      return `商品概览：${productStats.active} 款上架商品，${productStats.lowStock} 款低库存，本周销售 ¥${orderStats.weeklyRevenue.toLocaleString()}。`;
    case 'products_list':
      return `共有 ${productStats.total} 款商品，${productStats.active} 款已上架。`;
    case 'products_low_stock':
      return `有 ${productStats.lowStock} 款商品库存不足（≤10件），请及时补货。`;
    case 'products_slow_moving':
      return `有 ${productStats.slowMoving} 款商品滞销，建议促销或调价。`;
    case 'products_hot':
      return `有 ${productStats.hotProducts} 款热销商品。`;
    case 'products_new':
      return '最新上架的商品如下。';
    case 'categories_list':
      return `共有 ${categoryStats.total} 个分类，${categoryStats.active} 个启用中。`;
    case 'brands_list':
      return `共有 ${brandStats.total} 个品牌，${brandStats.active} 个启用中。`;
    case 'analytics':
      return `本周销售 ¥${orderStats.weeklyRevenue.toLocaleString()}，本月累计 ¥${orderStats.monthlyRevenue.toLocaleString()}。`;
    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('[Product 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("product_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('[Product 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 返回内容为空');
    }

    // 解析 JSON - 处理可能的 markdown 代码块包裹
    let jsonContent = content.trim();
    
    // 移除 ```json 和 ``` 包裹
    const jsonMatch = jsonContent.match(/```(?:json)?\s*([\s\S]*?)```/);
    if (jsonMatch) {
      jsonContent = jsonMatch[1].trim();
    }

    console.log('[Product 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('[Product 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('[Product GenUI] Request:', { message, context });

    // 获取商品数据
    const data = await fetchProductData(supabase, context);
    const { productStats, categoryStats, brandStats, orderStats, products, categories, brands } = data;

    // 构建数据上下文
    const dataContext = `
商品统计:
- 总商品数: ${productStats.total}
- 上架商品: ${productStats.active}
- 下架商品: ${productStats.inactive}
- 低库存(≤10件): ${productStats.lowStock}
- 断货(0库存): ${productStats.outOfStock}
- 滞销商品(月销<5且库存>20): ${productStats.slowMoving}
- 热销商品: ${productStats.hotProducts}
- 推荐商品: ${productStats.recommended}
- 平均价格: ¥${productStats.avgPrice}

分类统计:
- 总分类数: ${categoryStats.total}
- 启用分类: ${categoryStats.active}
- 顶级分类: ${categoryStats.topLevel}

品牌统计:
- 总品牌数: ${brandStats.total}
- 启用品牌: ${brandStats.active}

销售统计:
- 本周订单: ${orderStats.weeklyOrders} 笔
- 本周销售: ¥${orderStats.weeklyRevenue.toLocaleString()}
- 本月订单: ${orderStats.monthlyOrders} 笔
- 本月销售: ¥${orderStats.monthlyRevenue.toLocaleString()}

低库存商品样例(前5):
${products.filter((p: any) => p.is_active && p.stock_quantity <= 10).slice(0, 5).map((p: any) => `- ${p.name}: 库存${p.stock_quantity}件, ¥${p.price}`).join('\n')}

滞销商品样例(前5):
${products.filter((p: any) => p.is_active && (p.monthly_sales || 0) < 5 && p.stock_quantity > 20).slice(0, 5).map((p: any) => `- ${p.name}: 月销${p.monthly_sales || 0}件, 库存${p.stock_quantity}件`).join('\n')}
`;

    // 尝试使用 AI 动态生成
    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('[Product 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('[Product GenUI] AI generated schema successfully');
        } else {
          // AI 没有返回 schema，使用回退
          throw new Error('AI 未返回有效 schema');
        }
      } catch (aiError) {
        console.warn('[Product GenUI] AI fallback to template:', aiError);
        // 回退到模板模式
        const intent = detectIntent(message, context);
        uiSchema = generateUIByIntent(intent, data);
        answer = generateAnswer(intent, data);
      }
    } else {
      // 使用模板模式
      const intent = detectIntent(message, context);
      console.log('[Product GenUI] Using template mode, intent:', intent);
      uiSchema = generateUIByIntent(intent, data);
      answer = generateAnswer(intent, data);
    }

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

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

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

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

// 辅助函数：根据意图生成 UI
function generateUIByIntent(intent: string, data: any): UISchema {
  switch (intent) {
    case 'products_list':
      return generateProductsListUI(data);
    case 'products_low_stock':
      return generateProductsListUI(data, 'low_stock');
    case 'products_slow_moving':
      return generateProductsListUI(data, 'slow_moving');
    case 'products_hot':
      return generateProductsListUI(data, 'hot');
    case 'products_new':
      return generateProductsListUI(data, 'new');
    case 'categories_list':
      return generateCategoriesListUI(data);
    case 'brands_list':
      return generateBrandsListUI(data);
    case 'analytics':
      return generateAnalyticsUI(data);
    case 'help':
      return generateHelpUI();
    case 'dashboard':
    default:
      return generateDashboardUI(data);
  }
}