/**
 * 营销版块 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 MarketingInsight {
  id: string;
  type: 'warning' | 'success' | 'opportunity' | 'alert' | 'suggestion' | 'info';
  priority: 'low' | 'medium' | 'high' | 'urgent';
  category: 'campaign' | 'coupon' | 'sales' | 'customer';
  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?: MarketingInsight[];
  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'|'area', 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 fetchMarketingData(supabase: any, context?: GenUIRequest['context']) {
  console.log('[Marketing GenUI] Fetching marketing data...', context);
  
  const now = new Date();
  const thirtyDaysAgo = new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000);
  const sevenDaysAgo = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
  const threeDaysLater = new Date(now.getTime() + 3 * 24 * 60 * 60 * 1000);

  const [couponsRes, campaignsRes, flashSalesRes, ordersRes, groupBuyRes] = await Promise.all([
    supabase.from('coupons').select('*').order('created_at', { ascending: false }).limit(100),
    supabase.from('marketing_campaigns').select('*').order('created_at', { ascending: false }).limit(50),
    supabase.from('flash_sales').select('*, products(name, image_url, price)').order('start_time', { ascending: false }).limit(50),
    supabase.from('orders').select('id, total_amount, status, created_at').gte('created_at', thirtyDaysAgo.toISOString()).order('created_at', { ascending: false }).limit(200),
    supabase.from('group_buy_activities').select('*, products(name, image_url)').order('created_at', { ascending: false }).limit(30),
  ]);

  const coupons = couponsRes.data || [];
  const campaigns = campaignsRes.data || [];
  const flashSales = flashSalesRes.data || [];
  const orders = ordersRes.data || [];
  const groupBuy = groupBuyRes.data || [];

  // 计算优惠券统计
  const couponStats = {
    active: coupons.filter((c: any) => c.status === 'active').length,
    expiringSoon: coupons.filter((c: any) => {
      const endDate = new Date(c.end_date);
      return c.status === 'active' && endDate <= threeDaysLater && endDate > now;
    }).length,
    expired: coupons.filter((c: any) => c.status === 'expired' || new Date(c.end_date) < now).length,
    total: coupons.length,
    totalUsed: coupons.reduce((sum: number, c: any) => sum + (c.used_quantity || 0), 0),
  };

  // 计算活动统计
  const campaignStats = {
    active: campaigns.filter((c: any) => c.status === 'active').length,
    pending: campaigns.filter((c: any) => c.status === 'pending').length,
    draft: campaigns.filter((c: any) => c.status === 'draft').length,
    completed: campaigns.filter((c: any) => c.status === 'completed').length,
    total: campaigns.length,
  };

  // 计算秒杀统计
  const flashSaleStats = {
    active: flashSales.filter((f: any) => {
      const start = new Date(f.start_time);
      const end = new Date(f.end_time);
      return now >= start && now <= end && f.status === 'active';
    }).length,
    upcoming: flashSales.filter((f: any) => new Date(f.start_time) > now).length,
    totalSold: flashSales.reduce((sum: number, f: any) => sum + (f.sold_count || 0), 0),
    total: flashSales.length,
  };

  // 拼团统计
  const groupBuyStats = {
    active: groupBuy.filter((g: any) => g.status === 'active').length,
    total: groupBuy.length,
    totalSold: groupBuy.reduce((sum: number, g: any) => sum + (g.sold_count || 0), 0),
  };

  // 计算销售统计
  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('[Marketing GenUI] Data fetched:', { 
    couponsCount: coupons.length,
    campaignsCount: campaigns.length,
    flashSalesCount: flashSales.length,
  });

  // 生成营销洞察
  const insights = generateMarketingInsights(couponStats, campaignStats, flashSaleStats, orderStats);

  return {
    coupons,
    campaigns,
    flashSales,
    groupBuy,
    couponStats,
    campaignStats,
    flashSaleStats,
    groupBuyStats,
    orderStats,
    insights,
  };
}

// 生成营销相关洞察
function generateMarketingInsights(
  couponStats: any,
  campaignStats: any,
  flashSaleStats: any,
  orderStats: any
): MarketingInsight[] {
  const insights: MarketingInsight[] = [];
  const now = new Date();

  if (couponStats.expiringSoon > 0) {
    insights.push({
      id: 'expiring_coupons',
      type: 'warning',
      priority: 'high',
      category: 'coupon',
      title: `${couponStats.expiringSoon} 张优惠券即将过期`,
      description: '3天内即将过期，可考虑发送提醒或延期',
      confidence: 100,
      timestamp: now.toISOString(),
      metric: { label: '即将过期', value: couponStats.expiringSoon, trend: 'down' },
      action: { label: '查看详情', type: 'primary' }
    });
  }

  if (campaignStats.pending > 0) {
    insights.push({
      id: 'pending_campaigns',
      type: 'alert',
      priority: 'high',
      category: 'campaign',
      title: `${campaignStats.pending} 个活动待审批`,
      description: 'AI 已准备营销活动方案，请审批后执行',
      confidence: 100,
      timestamp: now.toISOString(),
      metric: { label: '待审批', value: campaignStats.pending, trend: 'neutral' },
      action: { label: '立即审批', type: 'primary' }
    });
  }

  if (flashSaleStats.active > 0) {
    insights.push({
      id: 'active_flash_sales',
      type: 'success',
      priority: 'medium',
      category: 'campaign',
      title: `${flashSaleStats.active} 个秒杀活动进行中`,
      description: `已售出 ${flashSaleStats.totalSold} 件商品`,
      confidence: 100,
      timestamp: now.toISOString(),
      metric: { label: '进行中', value: flashSaleStats.active, trend: 'up' },
      progress: { current: flashSaleStats.totalSold, target: 100, label: '销量' }
    });
  }

  const weeklyGrowth = orderStats.weeklyRevenue > 0 ? 
    Math.round((orderStats.weeklyRevenue / (orderStats.monthlyRevenue / 4)) * 100 - 100) : 0;
  
  insights.push({
    id: 'weekly_performance',
    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: ['概览', '工作台', '仪表盘', '总览', '首页', '看看'],
  coupons_list: ['优惠券', '折扣券', '券'],
  coupons_expiring: ['即将过期', '快过期', '快到期'],
  campaigns_list: ['活动', '营销活动', '促销'],
  campaigns_pending: ['待审批', '待审核', '待批准'],
  flash_sales: ['秒杀', '限时', '限时折扣', '闪购'],
  group_buy: ['拼团', '团购', '多人拼'],
  analytics: ['数据', '分析', '统计', '报表', '业绩'],
  help: ['帮助', '怎么', '如何', '教我', '指南'],
};

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

  if (INTENT_KEYWORDS.coupons_list.some(kw => lower.includes(kw))) {
    if (INTENT_KEYWORDS.coupons_expiring.some(kw => lower.includes(kw))) return 'coupons_expiring';
    return 'coupons_list';
  }
  if (INTENT_KEYWORDS.campaigns_list.some(kw => lower.includes(kw))) {
    if (INTENT_KEYWORDS.campaigns_pending.some(kw => lower.includes(kw))) return 'campaigns_pending';
    return 'campaigns_list';
  }
  if (INTENT_KEYWORDS.campaigns_pending.some(kw => lower.includes(kw))) return 'campaigns_pending';
  if (INTENT_KEYWORDS.flash_sales.some(kw => lower.includes(kw))) return 'flash_sales';
  if (INTENT_KEYWORDS.group_buy.some(kw => lower.includes(kw))) return 'group_buy';
  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 生成器 (回退模式)
// ========================

function generateDashboardUI(data: any): UISchema {
  const { couponStats, campaignStats, flashSaleStats, orderStats } = data;
  
  const urgentItems = [];
  if (campaignStats.pending > 0) {
    urgentItems.push({
      type: 'alert',
      props: { type: 'warning', title: `${campaignStats.pending} 个活动待审批`, description: 'AI 已生成活动方案，请审批执行' },
    });
  }
  if (couponStats.expiringSoon > 0) {
    urgentItems.push({
      type: 'alert',
      props: { type: 'error', title: `${couponStats.expiringSoon} 张优惠券即将过期`, description: '3天内过期，请及时处理' },
    });
  }

  return {
    layout: 'vertical',
    gap: 'md',
    components: [
      ...(urgentItems.length > 0 ? urgentItems : [{ type: 'alert', props: { type: 'success', title: '营销状态良好', description: '暂无紧急事项需要处理' } }]),
      {
        type: 'stats_row',
        props: {
          items: [
            { label: '有效优惠券', value: couponStats.active, color: 'info' },
            { label: '进行中活动', value: campaignStats.active, color: 'success' },
            { label: '秒杀活动', value: flashSaleStats.active, color: 'warning' },
            { label: '本周销售', value: `¥${orderStats.weeklyRevenue.toLocaleString()}`, color: 'success' },
          ],
        },
      },
    ],
  };
}

function generateAnswer(intent: string, data: any): string {
  const { couponStats, campaignStats, flashSaleStats, orderStats } = data;
  switch (intent) {
    case 'dashboard': return `营销概览：${couponStats.active} 张有效优惠券，${campaignStats.active} 个进行中活动，本周销售 ¥${orderStats.weeklyRevenue.toLocaleString()}。`;
    case 'coupons_list': return `共有 ${couponStats.total} 张优惠券，${couponStats.active} 张有效中。`;
    case 'coupons_expiring': return `有 ${couponStats.expiringSoon} 张优惠券即将过期。`;
    case 'campaigns_list': return `共有 ${campaignStats.total} 个营销活动，${campaignStats.active} 个进行中。`;
    case 'campaigns_pending': return `有 ${campaignStats.pending} 个活动待审批。`;
    case 'flash_sales': return `共有 ${flashSaleStats.total} 个秒杀活动，${flashSaleStats.active} 个进行中。`;
    case 'group_buy': return `共有 ${data.groupBuyStats.total} 个拼团活动。`;
    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('[Marketing 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("marketing_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('[Marketing 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('[Marketing 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('[Marketing 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('[Marketing GenUI] Request:', { message, context });

    const data = await fetchMarketingData(supabase, context);
    const { couponStats, campaignStats, flashSaleStats, groupBuyStats, orderStats, coupons, campaigns, flashSales } = data;

    // 构建数据上下文
    const dataContext = `
营销统计:
- 有效优惠券: ${couponStats.active} 张
- 即将过期: ${couponStats.expiringSoon} 张
- 已使用优惠券: ${couponStats.totalUsed} 张
- 营销活动总数: ${campaignStats.total} 个
- 进行中活动: ${campaignStats.active} 个
- 待审批活动: ${campaignStats.pending} 个
- 进行中秒杀: ${flashSaleStats.active} 个
- 秒杀已售: ${flashSaleStats.totalSold} 件
- 进行中拼团: ${groupBuyStats.active} 个

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

即将过期优惠券样例(前5):
${coupons.filter((c: any) => c.status === 'active' && new Date(c.end_date) <= new Date(Date.now() + 3 * 24 * 60 * 60 * 1000)).slice(0, 5).map((c: any) => `- ${c.name}: ${c.discount_value}${c.type === 'percentage' ? '%' : '元'}折扣`).join('\n') || '无'}

待审批活动样例(前5):
${campaigns.filter((c: any) => c.status === 'pending').slice(0, 5).map((c: any) => `- ${c.name}: ${c.type}`).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('[Marketing 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('[Marketing GenUI] AI generated schema successfully');
        } else {
          throw new Error('AI 未返回有效 schema');
        }
      } catch (aiError) {
        console.warn('[Marketing GenUI] AI fallback to template:', aiError);
        const intent = detectIntent(message, context);
        uiSchema = generateDashboardUI(data);
        answer = generateAnswer(intent, data);
      }
    } else {
      const intent = detectIntent(message, context);
      console.log('[Marketing GenUI] Using template mode, intent:', intent);
      uiSchema = generateDashboardUI(data);
      answer = generateAnswer(intent, data);
    }

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

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

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

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