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",
};

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

    // Get auth header
    const authHeader = req.headers.get("Authorization");
    if (!authHeader) {
      return new Response(JSON.stringify({ error: "Unauthorized" }), {
        status: 401,
        headers: { ...corsHeaders, "Content-Type": "application/json" },
      });
    }

    // Fetch comprehensive business data
    const today = new Date();
    const startOfMonth = new Date(today.getFullYear(), today.getMonth(), 1).toISOString();
    const startOfWeek = new Date(today.setDate(today.getDate() - today.getDay())).toISOString();
    const yesterday = new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString();
    const last7Days = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000).toISOString();

    // Orders data
    const [
      { data: monthOrders },
      { data: weekOrders },
      { data: pendingOrders },
      { data: recentOrders }
    ] = await Promise.all([
      supabase.from("orders").select("total_amount, status").gte("created_at", startOfMonth),
      supabase.from("orders").select("total_amount, status").gte("created_at", startOfWeek),
      supabase.from("orders").select("id").eq("status", "pending"),
      supabase.from("orders").select("total_amount, status, created_at").gte("created_at", last7Days).order("created_at", { ascending: false })
    ]);

    // Products data
    const [
      { data: lowStockProducts },
      { data: hotProducts },
      { count: totalProducts }
    ] = await Promise.all([
      supabase.from("products").select("name, stock_quantity").eq("is_active", true).lt("stock_quantity", 10),
      supabase.from("products").select("name, monthly_sales").eq("is_active", true).eq("is_hot", true).order("monthly_sales", { ascending: false }).limit(5),
      supabase.from("products").select("*", { count: "exact", head: true }).eq("is_active", true)
    ]);

    // Marketing data
    const [
      { data: activeCampaigns },
      { data: pendingCampaigns },
      { data: activeCoupons }
    ] = await Promise.all([
      supabase.from("marketing_campaigns").select("id, name, type").eq("status", "active"),
      supabase.from("marketing_campaigns").select("id, name, type").eq("status", "pending"),
      supabase.from("coupons").select("id, name, used_quantity, total_quantity").eq("status", "active")
    ]);

    // After-sales data
    const [
      { data: pendingAfterSales },
      { data: recentAfterSales }
    ] = await Promise.all([
      supabase.from("after_sales_requests").select("id, type").eq("status", "pending"),
      supabase.from("after_sales_requests").select("type, status, created_at").gte("created_at", last7Days)
    ]);

    // Users data
    const [
      { data: newUsers },
      { count: totalUsers }
    ] = await Promise.all([
      supabase.from("profiles").select("id").gte("created_at", startOfWeek),
      supabase.from("profiles").select("*", { count: "exact", head: true })
    ]);

    // Calculate metrics
    const monthRevenue = monthOrders?.reduce((sum, o) => o.status !== "cancelled" ? sum + (o.total_amount || 0) : sum, 0) || 0;
    const weekRevenue = weekOrders?.reduce((sum, o) => o.status !== "cancelled" ? sum + (o.total_amount || 0) : sum, 0) || 0;
    const pendingOrdersCount = pendingOrders?.length || 0;
    const lowStockCount = lowStockProducts?.length || 0;
    const pendingAfterSalesCount = pendingAfterSales?.length || 0;
    const newUsersCount = newUsers?.length || 0;
    const activeCampaignsCount = activeCampaigns?.length || 0;
    const pendingCampaignsCount = pendingCampaigns?.length || 0;

    // Coupon usage rate
    const couponUsage = activeCoupons?.map(c => ({
      name: c.name,
      rate: c.total_quantity > 0 ? Math.round((c.used_quantity || 0) / c.total_quantity * 100) : 0
    })) || [];

    // Build data summary
    const dataSummary = `
店长工作台经营数据汇总：

【销售概况】
- 本月销售额：¥${monthRevenue.toLocaleString()}
- 本周销售额：¥${weekRevenue.toLocaleString()}
- 待处理订单：${pendingOrdersCount}笔
- 最近7天订单数：${recentOrders?.length || 0}笔

【商品状况】
- 在售商品总数：${totalProducts || 0}件
- 库存预警商品：${lowStockCount}件
- 低库存商品列表：${lowStockProducts?.slice(0, 5).map(p => `${p.name}(${p.stock_quantity}件)`).join('、') || '无'}
- 热销商品TOP5：${hotProducts?.map(p => `${p.name}(月销${p.monthly_sales})`).join('、') || '无数据'}

【营销活动】
- 进行中活动：${activeCampaignsCount}个
- 待审批活动：${pendingCampaignsCount}个
- 优惠券使用情况：${couponUsage.slice(0, 3).map(c => `${c.name}(${c.rate}%)`).join('、') || '无活跃优惠券'}

【售后服务】
- 待处理售后：${pendingAfterSalesCount}件
- 本周售后总量：${recentAfterSales?.length || 0}件
- 售后类型分布：${pendingAfterSales?.reduce((acc, a) => { acc[a.type] = (acc[a.type] || 0) + 1; return acc; }, {} as Record<string, number>) ? Object.entries(pendingAfterSales?.reduce((acc, a) => { acc[a.type] = (acc[a.type] || 0) + 1; return acc; }, {} as Record<string, number>) || {}).map(([k, v]) => `${k}:${v}件`).join('、') : '无'}

【用户增长】
- 总用户数：${totalUsers || 0}
- 本周新增用户：${newUsersCount}人
`;

    // Call Lovable AI Gateway
    const LOVABLE_API_KEY = Deno.env.get("LOVABLE_API_KEY");
    if (!LOVABLE_API_KEY) {
      throw new Error("LOVABLE_API_KEY is not configured");
    }

    const aiResponse = await fetch(_AI_CHAT_URL, {
      method: "POST",
      headers: {
        Authorization: `Bearer ${_AI_CHAT_KEY}`,
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        model: _mapAiModel(await getModelForPurpose("manager_insights")),
        messages: [
          {
            role: "system",
            content: `你是一位资深的电商店长AI助手"小管"，负责从全局视角分析店铺经营状况。
根据提供的数据，生成4-6条经营洞察，涵盖销售、库存、营销、售后、用户等多个维度。

洞察类型说明：
- alert: 需要立即关注的预警（库存不足、订单积压、售后激增等）
- trend: 业务趋势分析（销售增长、用户变化等）
- suggestion: 经营建议（来自各部门Agent的协调建议）
- feedback: 各Agent执行反馈（正面进展或改进信息）

返回JSON数组格式，每条洞察包含：
- id: 唯一标识（如"1", "2"）
- type: 洞察类型（alert/trend/suggestion/feedback）
- title: 简短标题（10字以内）
- description: 详细描述（30-50字，包含具体数据）
- priority: 优先级（high/medium/low）
- time: 时间标记（如"刚刚"、"5分钟前"、"1小时前"）
- agent: 来源Agent（小品/小营/小服/小财，可选）

优先级分配规则：
- high: 库存严重不足、大量待处理订单/售后、销售显著下降
- medium: 营销活动待审批、用户增长放缓、部分商品缺货
- low: 正常业务趋势、执行进度反馈

请基于实际数据生成有价值的经营洞察，帮助店长快速掌握全店运营状况。`
          },
          {
            role: "user",
            content: dataSummary
          }
        ],
        temperature: 0.7,
      }),
    });

    if (!aiResponse.ok) {
      const errorText = await aiResponse.text();
      console.error("AI Gateway error:", aiResponse.status, errorText);
      // 限流/额度不足：返回 200 + 友好提示，避免前端白屏
      if (aiResponse.status === 429 || aiResponse.status === 402) {
        return new Response(JSON.stringify({
          success: true,
          rateLimited: aiResponse.status === 429,
          paymentRequired: aiResponse.status === 402,
          insights: [{
            id: "rate-limit",
            type: "alert",
            title: aiResponse.status === 429 ? "AI 暂时繁忙" : "AI 额度不足",
            description: aiResponse.status === 429
              ? "AI 调用过于频繁，已自动降级。请稍后刷新查看完整洞察。"
              : "Lovable AI 余额不足，请到 Settings → Workspace → Usage 充值。",
            priority: "low",
            time: "刚刚",
          }],
          summary: { monthRevenue: 0, weekRevenue: 0, pendingOrdersCount: 0, lowStockCount: 0, pendingAfterSalesCount: 0, newUsersCount: 0 },
        }), { headers: { ...corsHeaders, "Content-Type": "application/json" } });
      }
      throw new Error(`AI Gateway error: ${aiResponse.status}`);
    }

    const aiData = await aiResponse.json();
    const content = aiData.choices?.[0]?.message?.content || "[]";

    // Parse AI response
    let insights = [];
    try {
      const jsonMatch = content.match(/\[[\s\S]*\]/);
      if (jsonMatch) {
        insights = JSON.parse(jsonMatch[0]);
      }
    } catch (parseError) {
      console.error("Failed to parse AI response:", parseError);
      // Return default insights on parse failure
      insights = [
        {
          id: "1",
          type: "alert",
          title: "数据分析中",
          description: "正在分析店铺经营数据，请稍后刷新查看",
          priority: "medium",
          time: "刚刚"
        }
      ];
    }

    return new Response(JSON.stringify({ 
      success: true,
      insights, 
      summary: { monthRevenue, weekRevenue, pendingOrdersCount, lowStockCount, pendingAfterSalesCount, newUsersCount } 
    }), {
      headers: { ...corsHeaders, "Content-Type": "application/json" },
    });
  } catch (error) {
    console.error("Manager insights error:", error);
    const msg = error instanceof Error ? error.message : String(error);
    const isRateLimit = /\b429\b/.test(msg);
    const isPayment = /\b402\b/.test(msg);
    // 任何下游错误都不让前端白屏：返回 200 + 友好兜底
    return new Response(JSON.stringify({
      success: true,
      degraded: true,
      rateLimited: isRateLimit,
      paymentRequired: isPayment,
      error: msg,
      insights: [{
        id: "fallback",
        type: "alert",
        title: isRateLimit ? "AI 暂时繁忙" : isPayment ? "AI 额度不足" : "洞察暂不可用",
        description: isRateLimit
          ? "AI 调用过于频繁，已自动降级。请稍后刷新。"
          : isPayment
          ? "Lovable AI 余额不足，请到 Settings → Workspace → Usage 充值。"
          : "数据分析服务暂时不可用，请稍后再试。",
        priority: "low",
        time: "刚刚",
      }],
      summary: { monthRevenue: 0, weekRevenue: 0, pendingOrdersCount: 0, lowStockCount: 0, pendingAfterSalesCount: 0, newUsersCount: 0 },
    }), {
      status: 200,
      headers: { ...corsHeaders, "Content-Type": "application/json" },
    });
  }
});
