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 MarketingData {
  orders: any[];
  campaigns: any[];
  coupons: any[];
  flashSales: any[];
  products: any[];
}

interface Insight {
  id: string;
  type: 'opportunity' | 'warning' | 'auto_executed' | 'suggestion' | 'alert';
  title: string;
  description: string;
  priority?: 'high' | 'medium' | 'low';
  metric?: {
    label: string;
    value: string;
    trend: 'up' | 'down' | 'neutral';
  };
  action?: {
    label: string;
  };
  time: string;
}

async function fetchMarketingData(supabase: any): Promise<MarketingData> {
  const thirtyDaysAgo = new Date();
  thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);
  const thirtyDaysAgoStr = thirtyDaysAgo.toISOString();

  const sevenDaysAgo = new Date();
  sevenDaysAgo.setDate(sevenDaysAgo.getDate() - 7);
  const sevenDaysAgoStr = sevenDaysAgo.toISOString();

  // 并行查询所有数据
  const [ordersResult, campaignsResult, couponsResult, flashSalesResult, productsResult] = await Promise.all([
    supabase
      .from('orders')
      .select('id, total_amount, status, created_at, user_id')
      .gte('created_at', thirtyDaysAgoStr)
      .order('created_at', { ascending: false })
      .limit(100),
    supabase
      .from('marketing_campaigns')
      .select('*')
      .order('created_at', { ascending: false })
      .limit(20),
    supabase
      .from('coupons')
      .select('*')
      .order('created_at', { ascending: false })
      .limit(20),
    supabase
      .from('flash_sales')
      .select('*')
      .order('created_at', { ascending: false })
      .limit(10),
    supabase
      .from('products')
      .select('id, name, category, price, stock_quantity, monthly_sales, praise_rate, is_active')
      .eq('is_active', true)
      .order('monthly_sales', { ascending: false })
      .limit(50)
  ]);

  return {
    orders: ordersResult.data || [],
    campaigns: campaignsResult.data || [],
    coupons: couponsResult.data || [],
    flashSales: flashSalesResult.data || [],
    products: productsResult.data || []
  };
}

function generateDataSummary(data: MarketingData): string {
  const now = new Date();
  const sevenDaysAgo = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
  
  // 订单统计
  const recentOrders = data.orders.filter(o => new Date(o.created_at) >= sevenDaysAgo);
  const totalRevenue = recentOrders.reduce((sum, o) => sum + (o.total_amount || 0), 0);
  const completedOrders = recentOrders.filter(o => o.status === 'completed').length;
  const pendingOrders = recentOrders.filter(o => o.status === 'pending').length;
  
  // 优惠券统计
  const activeCoupons = data.coupons.filter(c => c.status === 'active');
  const expiringSoonCoupons = activeCoupons.filter(c => {
    const endDate = new Date(c.end_date);
    const threeDaysLater = new Date(now.getTime() + 3 * 24 * 60 * 60 * 1000);
    return endDate <= threeDaysLater;
  });
  
  // 活动统计
  const activeCampaigns = data.campaigns.filter(c => c.status === 'active');
  const pendingCampaigns = data.campaigns.filter(c => c.status === 'pending_approval' || c.status === 'draft');
  
  // 秒杀统计
  const activeFlashSales = data.flashSales.filter(f => f.status === 'active');
  
  // 商品统计
  const lowStockProducts = data.products.filter(p => p.stock_quantity < 10);
  const topSellingProducts = data.products.slice(0, 5);
  
  return `
## 营销数据概况（过去7天）

### 订单数据
- 总订单数: ${recentOrders.length}
- 总收入: ¥${totalRevenue.toFixed(2)}
- 已完成: ${completedOrders}
- 待处理: ${pendingOrders}

### 优惠券
- 活跃优惠券: ${activeCoupons.length}
- 即将过期（3天内）: ${expiringSoonCoupons.length}
${expiringSoonCoupons.length > 0 ? `- 即将过期券: ${expiringSoonCoupons.map(c => c.name).join(', ')}` : ''}

### 营销活动
- 进行中: ${activeCampaigns.length}
- 待审批/草稿: ${pendingCampaigns.length}

### 秒杀活动
- 进行中: ${activeFlashSales.length}

### 商品库存
- 低库存商品（<10件）: ${lowStockProducts.length}
${lowStockProducts.length > 0 ? `- 低库存: ${lowStockProducts.map(p => p.name).slice(0, 3).join(', ')}` : ''}

### 热销商品TOP5
${topSellingProducts.map((p, i) => `${i + 1}. ${p.name} (月销${p.monthly_sales || 0})`).join('\n')}
`;
}

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

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

每条洞察必须包含：
1. type: 类型（opportunity=发现机会, warning=异常预警, suggestion=AI建议, auto_executed=已自动执行）
2. title: 简短标题（10-20字）
3. description: 详细描述（30-50字）
4. metric: 可选，关键指标 {label: 指标名, value: 数值, trend: up/down/neutral}
5. action: 可选，建议操作 {label: 按钮文字}

返回JSON数组格式，不要包含其他文字。示例：
[
  {
    "type": "warning",
    "title": "库存预警",
    "description": "有3款热销商品库存低于10件，建议及时补货。",
    "metric": {"label": "低库存商品", "value": "3款", "trend": "down"},
    "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: _mapAiModel(await getModelForPurpose("marketing_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);
    
    if (response.status === 429) {
      throw new Error('Rate limit exceeded, please try again later');
    }
    if (response.status === 402) {
      throw new Error('Payment required, please add credits');
    }
    throw new Error(`AI service error: ${response.status}`);
  }

  const data = await response.json();
  const content = data.choices?.[0]?.message?.content || '';
  
  console.log('AI response content:', content);
  
  // 解析JSON响应
  try {
    // 尝试提取JSON数组
    const jsonMatch = content.match(/\[[\s\S]*\]/);
    if (jsonMatch) {
      const insights = JSON.parse(jsonMatch[0]);
      return insights.map((insight: any, index: number) => ({
        id: `ai-${Date.now()}-${index}`,
        type: insight.type || 'suggestion',
        title: insight.title || '洞察',
        description: insight.description || '',
        priority: insight.priority || 'medium',
        metric: insight.metric,
        action: insight.action,
        time: '刚刚'
      }));
    }
  } catch (parseError) {
    console.error('Failed to parse AI response:', parseError);
  }
  
  // 如果解析失败，返回默认洞察
  return [{
    id: `fallback-${Date.now()}`,
    type: 'suggestion',
    title: 'AI分析完成',
    description: content.slice(0, 100) || '数据分析中，请稍后刷新查看更多洞察。',
    priority: 'low',
    time: '刚刚'
  }];
}

serve(async (req) => {
  // Handle CORS preflight
  if (req.method === 'OPTIONS') {
    return new Response(null, { headers: corsHeaders });
  }

  try {
    // 创建Supabase客户端
    const supabaseUrl = Deno.env.get('SUPABASE_URL')!;
    const supabaseKey = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
    const supabase = createClient(supabaseUrl, supabaseKey);

    console.log('Fetching marketing data...');
    
    // 获取营销数据
    const marketingData = await fetchMarketingData(supabase);
    
    console.log('Data fetched:', {
      orders: marketingData.orders.length,
      campaigns: marketingData.campaigns.length,
      coupons: marketingData.coupons.length,
      flashSales: marketingData.flashSales.length,
      products: marketingData.products.length
    });

    // 生成数据摘要
    const dataSummary = generateDataSummary(marketingData);
    console.log('Data summary generated');

    // 调用AI生成洞察
    const insights = await generateInsightsWithAI(dataSummary);
    console.log('Generated insights:', insights.length);

    return new Response(JSON.stringify({ 
      success: true,
      insights,
      dataSnapshot: {
        ordersCount: marketingData.orders.length,
        campaignsCount: marketingData.campaigns.length,
        couponsCount: marketingData.coupons.length,
        generatedAt: new Date().toISOString()
      }
    }), {
      headers: { ...corsHeaders, 'Content-Type': 'application/json' },
    });

  } catch (error) {
    console.error('Error in marketing-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' },
    });
  }
});
