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 ServiceInsight {
  id: string;
  type: 'alert' | 'trend' | 'suggestion' | 'feedback';
  title: string;
  description: string;
  priority: 'high' | 'medium' | 'low';
  time: string;
}

async function fetchServiceData(supabase: any) {
  const sevenDaysAgo = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000).toISOString();
  const twentyFourHoursAgo = new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString();

  const [afterSalesResult, ordersResult, productsResult] = await Promise.all([
    supabase
      .from('after_sales_requests')
      .select('id, type, reason, status, product_id, created_at, processed_at, refund_amount')
      .gte('created_at', sevenDaysAgo)
      .order('created_at', { ascending: false })
      .limit(200),
    supabase
      .from('orders')
      .select('id, status, total_amount, created_at, user_id')
      .gte('created_at', sevenDaysAgo)
      .limit(300),
    supabase
      .from('products')
      .select('id, name, praise_rate')
      .limit(100)
  ]);

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

function generateDataSummary(data: any): string {
  const { afterSales, orders, products } = data;
  
  const twentyFourHoursAgo = Date.now() - 24 * 60 * 60 * 1000;
  
  // 售后统计
  const pendingRequests = afterSales.filter((a: any) => a.status === 'pending');
  const oldPendingRequests = pendingRequests.filter((a: any) => 
    new Date(a.created_at).getTime() < twentyFourHoursAgo
  );
  
  const processedToday = afterSales.filter((a: any) => 
    a.processed_at && new Date(a.processed_at).getTime() > twentyFourHoursAgo
  );
  
  // 售后类型分布
  const typeDistribution: Record<string, number> = {};
  afterSales.forEach((a: any) => {
    typeDistribution[a.type] = (typeDistribution[a.type] || 0) + 1;
  });
  
  // 退货原因分析
  const reasonDistribution: Record<string, number> = {};
  afterSales.forEach((a: any) => {
    if (a.reason) {
      reasonDistribution[a.reason] = (reasonDistribution[a.reason] || 0) + 1;
    }
  });
  
  // 问题商品统计
  const productIssues: Record<string, number> = {};
  afterSales.forEach((a: any) => {
    productIssues[a.product_id] = (productIssues[a.product_id] || 0) + 1;
  });
  
  const topIssueProductIds = Object.entries(productIssues)
    .sort(([,a], [,b]) => b - a)
    .slice(0, 5)
    .map(([id]) => id);
  
  const topIssueProducts = products.filter((p: any) => topIssueProductIds.includes(p.id));
  
  // 计算处理时效
  const processedRequests = afterSales.filter((a: any) => a.processed_at);
  const avgProcessTime = processedRequests.length > 0 
    ? processedRequests.reduce((sum: number, a: any) => {
        const processTime = new Date(a.processed_at).getTime() - new Date(a.created_at).getTime();
        return sum + processTime;
      }, 0) / processedRequests.length / (1000 * 60 * 60) // 转换为小时
    : 0;

  return `
## 客服数据概况（近7天）

### 售后工单
- 总工单数: ${afterSales.length}
- 待处理: ${pendingRequests.length}
- 超24小时未处理: ${oldPendingRequests.length}
- 今日已处理: ${processedToday.length}
- 平均处理时长: ${avgProcessTime.toFixed(1)}小时

### 工单类型分布
${Object.entries(typeDistribution).map(([type, count]) => `- ${type}: ${count}件`).join('\n')}

### 主要退货原因
${Object.entries(reasonDistribution).slice(0, 5).map(([reason, count]) => `- ${reason}: ${count}件`).join('\n')}

### 问题商品TOP5
${topIssueProducts.map((p: any, i: number) => `${i + 1}. ${p.name} (${productIssues[p.id]}件售后)`).join('\n')}

### 订单情况
- 近7天订单: ${orders.length}
- 待发货: ${orders.filter((o: any) => o.status === 'pending').length}
- 已完成: ${orders.filter((o: any) => o.status === 'completed').length}
`;
}

async function generateInsightsWithAI(dataSummary: string): Promise<ServiceInsight[]> {
  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=异常预警, trend=趋势分析, suggestion=改进建议, feedback=客户反馈）
2. title: 简短标题（10-20字）
3. description: 详细描述（30-50字）
4. priority: 优先级（high/medium/low）

返回JSON数组格式。示例：
[
  {
    "type": "alert",
    "title": "售后积压预警",
    "description": "有15个售后申请超过24小时未处理，建议优先安排人员处理",
    "priority": "high"
  }
]`;

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

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

    return new Response(JSON.stringify({ 
      success: true,
      insights,
      stats: {
        totalRequests: serviceData.afterSales.length,
        pendingCount: serviceData.afterSales.filter((a: any) => a.status === 'pending').length,
        generatedAt: new Date().toISOString()
      }
    }), {
      headers: { ...corsHeaders, 'Content-Type': 'application/json' },
    });

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