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 ProductInsight {
  id: string;
  type: 'low_stock' | 'slow_moving' | 'price_opportunity' | 'trending' | 'quality_issue' | 'alert' | 'warning' | 'suggestion';
  title: string;
  description: string;
  priority: 'high' | 'medium' | 'low';
  suggestedAction?: string;
  time: string;
}

async function fetchProductData(supabase: any) {
  const [productsResult, ordersResult, afterSalesResult] = await Promise.all([
    supabase
      .from('products')
      .select('id, name, brand, category, price, stock_quantity, monthly_sales, monthly_browse, praise_rate, is_active, is_hot, is_recommended, created_at')
      .eq('is_active', true)
      .order('monthly_sales', { ascending: false })
      .limit(100),
    supabase
      .from('orders')
      .select('id, total_amount, status, created_at')
      .gte('created_at', new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString())
      .limit(200),
    supabase
      .from('after_sales_requests')
      .select('id, product_id, type, reason, status, created_at')
      .gte('created_at', new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString())
      .limit(100)
  ]);

  return {
    products: productsResult.data || [],
    orders: ordersResult.data || [],
    afterSales: afterSalesResult.data || []
  };
}

function generateDataSummary(data: any): string {
  const { products, orders, afterSales } = data;
  
  // 库存分析
  const lowStockProducts = products.filter((p: any) => p.stock_quantity < 10);
  const outOfStockProducts = products.filter((p: any) => p.stock_quantity === 0);
  
  // 销售分析
  const topSellers = products.slice(0, 5);
  const slowMoving = products.filter((p: any) => (p.monthly_sales || 0) < 5);
  
  // 售后分析
  const returnRequests = afterSales.filter((a: any) => a.type === 'return' || a.type === 'refund');
  const productReturnCounts: Record<string, number> = {};
  returnRequests.forEach((r: any) => {
    productReturnCounts[r.product_id] = (productReturnCounts[r.product_id] || 0) + 1;
  });
  
  // 找出退货最多的商品
  const highReturnProductIds = Object.entries(productReturnCounts)
    .filter(([_, count]) => count >= 3)
    .map(([id]) => id);
  
  const highReturnProducts = products.filter((p: any) => highReturnProductIds.includes(p.id));
  
  // 新品表现
  const newProducts = products.filter((p: any) => {
    const createdDate = new Date(p.created_at);
    return Date.now() - createdDate.getTime() < 14 * 24 * 60 * 60 * 1000;
  });

  return `
## 商品数据概况

### 库存状况
- 在售商品总数: ${products.length}
- 低库存商品（<10件）: ${lowStockProducts.length}
- 缺货商品: ${outOfStockProducts.length}
${lowStockProducts.length > 0 ? `- 低库存商品: ${lowStockProducts.slice(0, 5).map((p: any) => `${p.name}(剩${p.stock_quantity})`).join(', ')}` : ''}

### 销售表现
- 热销TOP5: ${topSellers.map((p: any) => `${p.name}(月销${p.monthly_sales || 0})`).join(', ')}
- 滞销商品（月销<5）: ${slowMoving.length}款

### 售后情况
- 近30天退货/退款申请: ${returnRequests.length}
${highReturnProducts.length > 0 ? `- 退货率较高商品: ${highReturnProducts.map((p: any) => p.name).join(', ')}` : '- 暂无异常退货商品'}

### 新品表现
- 近14天新上架: ${newProducts.length}款
${newProducts.length > 0 ? `- 新品: ${newProducts.map((p: any) => `${p.name}(销量${p.monthly_sales || 0})`).join(', ')}` : ''}

### 商品评价
- 平均好评率: ${(products.reduce((sum: number, p: any) => sum + (p.praise_rate || 0), 0) / products.length * 100).toFixed(1)}%
`;
}

async function generateInsightsWithAI(dataSummary: string): Promise<ProductInsight[]> {
  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: 类型（alert=紧急预警, warning=注意事项, suggestion=建议优化, trending=趋势洞察）
2. title: 简短标题（10-20字）
3. description: 详细描述（30-50字）
4. priority: 优先级（high/medium/low）
5. suggestedAction: 建议操作（可选，10字以内）

返回JSON数组格式。示例：
[
  {
    "type": "alert",
    "title": "热销商品库存告急",
    "description": "iPhone 15等3款热销商品库存低于安全线，按当前销售速度预计5天售罄",
    "priority": "high",
    "suggestedAction": "立即补货"
  }
]`;

  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("product_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: `product-${Date.now()}-${index}`,
        type: insight.type || 'suggestion',
        title: insight.title || '洞察',
        description: insight.description || '',
        priority: insight.priority || 'medium',
        suggestedAction: insight.suggestedAction,
        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) => {
  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 product data...');
    const productData = await fetchProductData(supabase);
    
    console.log('Data fetched:', {
      products: productData.products.length,
      orders: productData.orders.length,
      afterSales: productData.afterSales.length
    });

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

    return new Response(JSON.stringify({ 
      success: true,
      insights,
      stats: {
        totalProducts: productData.products.length,
        lowStock: productData.products.filter((p: any) => p.stock_quantity < 10).length,
        generatedAt: new Date().toISOString()
      }
    }), {
      headers: { ...corsHeaders, 'Content-Type': 'application/json' },
    });

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