import { serve } from "https://deno.land/std@0.168.0/http/server.ts";
import { createClient } from "https://esm.sh/@supabase/supabase-js@2";
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 FinanceInsight {
  id: string;
  type: 'success' | 'warning' | 'info' | 'opportunity';
  title: string;
  description: string;
  action?: { label: string };
  timestamp: string;
}

async function fetchFinanceData(supabase: any) {
  const thirtyDaysAgo = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString();
  const sixtyDaysAgo = new Date(Date.now() - 60 * 24 * 60 * 60 * 1000).toISOString();

  const [ordersResult, transactionsResult, afterSalesResult] = 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')
      .gte('created_at', thirtyDaysAgo)
      .limit(200),
    supabase
      .from('after_sales_requests')
      .select('id, refund_amount, status, type, created_at')
      .gte('created_at', thirtyDaysAgo)
      .limit(100)
  ]);

  return {
    orders: ordersResult.data || [],
    transactions: transactionsResult.data || [],
    afterSales: afterSalesResult.data || []
  };
}

function generateDataSummary(data: any): string {
  const { orders, transactions, afterSales } = data;
  
  const now = new Date();
  const thirtyDaysAgo = new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000);
  const sixtyDaysAgo = new Date(now.getTime() - 60 * 24 * 60 * 60 * 1000);
  const today = now.toISOString().split('T')[0];
  const monthStart = new Date(now.getFullYear(), now.getMonth(), 1);
  
  // 本月订单
  const thisMonthOrders = orders.filter((o: any) => new Date(o.created_at) >= monthStart);
  const thisMonthRevenue = thisMonthOrders.reduce((sum: number, o: any) => sum + o.total_amount, 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);
  
  // 增长率
  const growthRate = lastMonthRevenue > 0 
    ? ((thisMonthRevenue - lastMonthRevenue) / lastMonthRevenue * 100) 
    : 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);
  
  // 待结算（已发货状态）
  const pendingSettlement = orders
    .filter((o: any) => o.status === 'delivered' || o.status === 'shipped')
    .reduce((sum: number, o: any) => sum + o.total_amount, 0);
  
  // 退款统计
  const refundRequests = afterSales.filter((a: any) => 
    (a.type === 'refund' || a.type === 'return') && a.status === 'approved'
  );
  const totalRefund = refundRequests.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);
  
  // 客单价
  const avgOrderValue = thisMonthOrders.length > 0 
    ? thisMonthRevenue / thisMonthOrders.length 
    : 0;
  
  // 订单状态分布
  const statusDistribution: Record<string, number> = {};
  orders.forEach((o: any) => {
    statusDistribution[o.status] = (statusDistribution[o.status] || 0) + 1;
  });

  return `
## 财务数据概况

### 营收概览
- 本月营收: ¥${thisMonthRevenue.toFixed(2)}
- 上月营收: ¥${lastMonthRevenue.toFixed(2)}
- 环比增长: ${growthRate >= 0 ? '+' : ''}${growthRate.toFixed(1)}%
- 今日营收: ¥${todayRevenue.toFixed(2)}
- 平均客单价: ¥${avgOrderValue.toFixed(2)}

### 结算情况
- 待结算金额: ¥${pendingSettlement.toFixed(2)}
- 本月退款: ¥${totalRefund.toFixed(2)}
- 退款单数: ${refundRequests.length}

### 会员充值
- 本月充值: ¥${rechargeAmount.toFixed(2)}

### 订单状态分布
${Object.entries(statusDistribution).map(([status, count]) => `- ${status}: ${count}单`).join('\n')}

### 本月订单数
- 总订单: ${thisMonthOrders.length}
- 完成订单: ${thisMonthOrders.filter((o: any) => o.status === 'completed').length}
- 待处理: ${thisMonthOrders.filter((o: any) => o.status === 'pending').length}
`;
}

async function generateInsightsWithAI(dataSummary: string): Promise<FinanceInsight[]> {
  const LOVABLE_API_KEY = Deno.env.get('LOVABLE_API_KEY');
  
  if (!LOVABLE_API_KEY) {
    throw new Error('AI service not configured');
  }

  const systemPrompt = `你是一个电商财务AI分析师。根据提供的财务数据，生成3-5条有价值的财务洞察。

每条洞察必须包含：
1. type: 类型（success=正向趋势, warning=风险预警, info=信息提示, opportunity=机会发现）
2. title: 简短标题（10-20字）
3. description: 详细描述（30-50字）
4. action: 可选，建议操作 {label: 按钮文字}

返回JSON数组格式。示例：
[
  {
    "type": "success",
    "title": "营收稳步增长",
    "description": "本月营收环比增长15%，保持良好增长势头，建议继续当前策略",
    "action": {"label": "查看详情"}
  }
]`;

  const response = await fetch(_AI_CHAT_URL, {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${_AI_CHAT_KEY}`,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      model: _USE_HUB ? _AI_CHAT_DEFAULT_MODEL : _mapAiModel(await getModelForPurpose("finance_insights")),
      messages: [
        { role: 'system', content: systemPrompt },
        { role: 'user', content: `请分析以下财务数据并生成洞察：\n\n${dataSummary}` }
      ],
      temperature: 0.7,
      max_tokens: 2000
    }),
  });

  if (!response.ok) {
    const errorText = await response.text();
    console.error('AI Gateway error:', response.status, errorText);
    throw new Error(`AI service error: ${response.status}`);
  }

  const data = await response.json();
  const content = data.choices?.[0]?.message?.content || '';
  
  try {
    const jsonMatch = content.match(/\[[\s\S]*\]/);
    if (jsonMatch) {
      const insights = JSON.parse(jsonMatch[0]);
      return insights.map((insight: any, index: number) => ({
        id: `finance-${Date.now()}-${index}`,
        type: insight.type || 'info',
        title: insight.title || '洞察',
        description: insight.description || '',
        priority: insight.priority || 'medium',
        action: insight.action,
        time: '刚刚'
      }));
    }
  } catch (parseError) {
    console.error('Failed to parse AI response:', parseError);
  }
  
  return [{
    id: `fallback-${Date.now()}`,
    type: 'info',
    title: 'AI分析完成',
    description: content.slice(0, 100) || '数据分析中',
    timestamp: new Date().toISOString()
  }];
}

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);

    console.log('Fetching finance data...');
    const financeData = await fetchFinanceData(supabase);
    
    console.log('Data fetched:', {
      orders: financeData.orders.length,
      transactions: financeData.transactions.length,
      afterSales: financeData.afterSales.length
    });

    const dataSummary = generateDataSummary(financeData);
    const insights = await generateInsightsWithAI(dataSummary);

    return new Response(JSON.stringify({ 
      success: true,
      insights,
      stats: {
        ordersCount: financeData.orders.length,
        generatedAt: new Date().toISOString()
      }
    }), {
      headers: { ...corsHeaders, 'Content-Type': 'application/json' },
    });

  } catch (error) {
    console.error('Error in finance-insights:', error);
    return new Response(JSON.stringify({ 
      success: false,
      error: (error instanceof Error ? error.message : 'Unknown error'),
      insights: []
    }), {
      status: 500,
      headers: { ...corsHeaders, 'Content-Type': 'application/json' },
    });
  }
});
