/**
 * 财务版块 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 FinanceInsight {
  id: string;
  type: 'warning' | 'success' | 'opportunity' | 'alert' | 'info';
  priority: 'low' | 'medium' | 'high' | 'urgent';
  category: 'revenue' | 'refund' | 'recharge' | 'settlement';
  title: string;
  description: string;
  timestamp: string;
  metric?: { label: string; value: string | number; trend?: 'up' | 'down' | 'neutral' };
  action?: { label: string; type?: 'primary' | 'secondary' };
}

interface GenUIResponse {
  answer: string;
  ui_schema?: UISchema;
  insights?: FinanceInsight[];
  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?: 'currency'|'date', 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 fetchFinanceData(supabase: any) {
  console.log('[Finance GenUI] Fetching finance data...');
  
  const now = new Date();
  const thirtyDaysAgo = new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000).toISOString();
  const sixtyDaysAgo = new Date(now.getTime() - 60 * 24 * 60 * 60 * 1000).toISOString();
  const today = now.toISOString().split('T')[0];
  const monthStart = new Date(now.getFullYear(), now.getMonth(), 1).toISOString();

  const [ordersResult, transactionsResult, afterSalesResult, pendingRefundsResult, balancesResult] = await Promise.all([
    supabase.from('orders').select('id, total_amount, status, created_at, user_id').gte('created_at', sixtyDaysAgo).order('created_at', { ascending: false }).limit(500),
    supabase.from('balance_transactions').select('id, amount, type, created_at, user_id, balance_before, balance_after').gte('created_at', thirtyDaysAgo).order('created_at', { ascending: false }).limit(300),
    supabase.from('after_sales_requests').select('id, refund_amount, status, type, created_at').gte('created_at', thirtyDaysAgo).limit(200),
    supabase.from('after_sales_requests').select('id, refund_amount, type, created_at').eq('status', 'pending').in('type', ['refund', 'return']),
    supabase.from('user_balances').select('id, user_id, balance, total_recharged, total_consumed').order('balance', { ascending: false }).limit(100)
  ]);

  const orders = ordersResult.data || [];
  const transactions = transactionsResult.data || [];
  const afterSales = afterSalesResult.data || [];
  const pendingRefunds = pendingRefundsResult.data || [];
  const balances = balancesResult.data || [];

  const thisMonthOrders = orders.filter((o: any) => new Date(o.created_at) >= new Date(monthStart));
  const thisMonthRevenue = thisMonthOrders.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.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 pendingSettlement = orders.filter((o: any) => o.status === 'shipped' || o.status === 'delivered').reduce((sum: number, o: any) => sum + (o.total_amount || 0), 0);
  const refundAmount = afterSales.filter((a: any) => a.status === 'approved').reduce((sum: number, a: any) => sum + (a.refund_amount || 0), 0);
  const rechargeAmount = transactions.filter((t: any) => t.type === 'recharge').reduce((sum: number, t: any) => sum + (t.amount || 0), 0);
  const growthRate = lastMonthRevenue > 0 ? ((thisMonthRevenue - lastMonthRevenue) / lastMonthRevenue * 100) : 0;

  const totalBalance = balances.reduce((sum: number, b: any) => sum + (b.balance || 0), 0);
  const totalRecharged = balances.reduce((sum: number, b: any) => sum + (b.total_recharged || 0), 0);

  console.log('[Finance GenUI] Data fetched:', { ordersCount: orders.length, transactionsCount: transactions.length });

  const insights = generateFinanceInsights({
    thisMonthRevenue, lastMonthRevenue, todayRevenue, pendingSettlement, refundAmount,
    rechargeAmount, growthRate, pendingRefundCount: pendingRefunds.length,
    pendingRefundAmount: pendingRefunds.reduce((sum: number, r: any) => sum + (r.refund_amount || 0), 0),
    totalBalance, totalRecharged
  });

  return {
    orders,
    transactions,
    pendingRefunds,
    balances,
    stats: {
      thisMonthRevenue, lastMonthRevenue, todayRevenue, pendingSettlement, refundAmount,
      rechargeAmount, growthRate, orderCount: thisMonthOrders.length, todayOrderCount: todayOrders.length,
      pendingRefundCount: pendingRefunds.length,
      pendingRefundAmount: pendingRefunds.reduce((sum: number, r: any) => sum + (r.refund_amount || 0), 0),
      totalBalance, totalRecharged, memberCount: balances.length
    },
    insights,
  };
}

function generateFinanceInsights(stats: any): FinanceInsight[] {
  const insights: FinanceInsight[] = [];
  const now = new Date();

  if (stats.pendingRefundCount > 0) {
    insights.push({
      id: 'pending_refunds',
      type: 'alert',
      priority: stats.pendingRefundCount >= 5 ? 'urgent' : 'high',
      category: 'refund',
      title: `${stats.pendingRefundCount} 笔退款待审批`,
      description: `待退款金额 ¥${stats.pendingRefundAmount.toLocaleString()}`,
      timestamp: now.toISOString(),
      metric: { label: '待审批', value: stats.pendingRefundCount, trend: 'up' },
      action: { label: '立即处理', type: 'primary' }
    });
  }

  insights.push({
    id: 'monthly_revenue',
    type: stats.growthRate >= 0 ? 'success' : 'warning',
    priority: 'medium',
    category: 'revenue',
    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.pendingSettlement > 0) {
    insights.push({
      id: 'pending_settlement',
      type: 'info',
      priority: 'medium',
      category: 'settlement',
      title: `待结算金额 ¥${stats.pendingSettlement.toLocaleString()}`,
      description: '已发货/已送达订单待结算',
      timestamp: now.toISOString(),
      metric: { label: '待结算', value: `¥${stats.pendingSettlement.toLocaleString()}`, trend: 'neutral' }
    });
  }

  return insights.slice(0, 6);
}

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

const INTENT_KEYWORDS: Record<string, string[]> = {
  'refunds': ['退款', '退货', '退款审批', '待退款'],
  'membership': ['充值', '储值', '会员储值', '余额'],
  'orders': ['订单', '收款', '付款', '收入', '交易', '销售', '营收', '流水'],
  'analytics': ['报表', '分析', '统计', '财务报表', '趋势'],
  'help': ['帮助', '怎么', '如何'],
};

function detectIntent(message: string | undefined): string {
  if (!message || typeof message !== 'string') return 'dashboard';
  const lowerMsg = message.toLowerCase();
  
  for (const [intent, keywords] of Object.entries(INTENT_KEYWORDS)) {
    for (const keyword of keywords) {
      if (lowerMsg.includes(keyword)) {
        console.log(`[Finance GenUI] Intent detected: ${intent}`);
        return intent;
      }
    }
  }
  return 'dashboard';
}

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

function generateDashboardUI(stats: any): UISchema {
  return {
    layout: 'vertical',
    gap: 'md',
    components: [
      {
        type: 'stats_row',
        props: {
          items: [
            { label: '本月营收', value: `¥${stats.thisMonthRevenue.toFixed(0)}`, color: 'success' },
            { label: '今日营收', value: `¥${stats.todayRevenue.toFixed(0)}`, color: 'default' },
            { label: '待结算', value: `¥${stats.pendingSettlement.toFixed(0)}`, color: 'warning' },
            { label: '待审批退款', value: `${stats.pendingRefundCount}笔`, color: stats.pendingRefundCount > 0 ? 'error' : 'default' }
          ],
        }
      }
    ],
  };
}

function generateAnswer(intent: string, stats: any): string {
  switch (intent) {
    case 'dashboard': return `财务概览：本月营收 ¥${stats.thisMonthRevenue.toLocaleString()}，今日 ¥${stats.todayRevenue.toLocaleString()}，${stats.pendingRefundCount} 笔待审批退款。`;
    case 'refunds': return `有 ${stats.pendingRefundCount} 笔退款待审批，金额 ¥${stats.pendingRefundAmount.toLocaleString()}。`;
    case 'membership': return `会员储值余额 ¥${stats.totalBalance.toLocaleString()}，累计充值 ¥${stats.totalRecharged.toLocaleString()}。`;
    case 'orders': return `本月 ${stats.orderCount} 笔订单，营收 ¥${stats.thisMonthRevenue.toLocaleString()}。`;
    case 'analytics': return `本月营收环比${stats.growthRate >= 0 ? '增长' : '下降'} ${Math.abs(stats.growthRate).toFixed(1)}%。`;
    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('[Finance 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("finance_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('[Finance 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('[Finance 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('[Finance 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('[Finance GenUI] Request:', { message, context });

    const data = await fetchFinanceData(supabase);
    const { stats, orders, transactions, pendingRefunds, balances } = data;

    // 构建数据上下文
    const dataContext = `
财务统计:
- 本月营收: ¥${stats.thisMonthRevenue.toLocaleString()}
- 上月营收: ¥${stats.lastMonthRevenue.toLocaleString()}
- 环比增长: ${stats.growthRate.toFixed(1)}%
- 今日营收: ¥${stats.todayRevenue.toLocaleString()}
- 今日订单: ${stats.todayOrderCount} 笔
- 待结算金额: ¥${stats.pendingSettlement.toLocaleString()}
- 待审批退款: ${stats.pendingRefundCount} 笔，金额 ¥${stats.pendingRefundAmount.toLocaleString()}
- 本月已退款: ¥${stats.refundAmount.toLocaleString()}

会员储值:
- 储值会员数: ${stats.memberCount} 人
- 会员总余额: ¥${stats.totalBalance.toLocaleString()}
- 累计充值: ¥${stats.totalRecharged.toLocaleString()}
- 本月充值: ¥${stats.rechargeAmount.toLocaleString()}

待审批退款样例(前5):
${pendingRefunds.slice(0, 5).map((r: any) => `- ${r.type === 'refund' ? '仅退款' : '退货退款'}: ¥${r.refund_amount || 0}`).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('[Finance 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('[Finance GenUI] AI generated schema successfully');
        } else {
          throw new Error('AI 未返回有效 schema');
        }
      } catch (aiError) {
        console.warn('[Finance GenUI] AI fallback to template:', aiError);
        const intent = detectIntent(message);
        uiSchema = generateDashboardUI(stats);
        answer = generateAnswer(intent, stats);
      }
    } else {
      const intent = detectIntent(message);
      console.log('[Finance GenUI] Using template mode, intent:', intent);
      uiSchema = generateDashboardUI(stats);
      answer = generateAnswer(intent, stats);
    }

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

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

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

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