/**
 * email-generate-replies Edge Function
 *
 * 批量处理收件箱中待 AI 回复的邮件，使用 Qwen API 生成回复草稿
 *
 * 处理流程：
 * 1. 查询收件箱中 status = "delivered" 的未处理邮件
 * 2. 检查是否已有对应的回复草稿（避免重复生成）
 * 3. 调用 Qwen Chat API 生成回复内容
 * 4. 创建草稿邮件（status = "draft"）
 */

import { serve } from "https://deno.land/std@0.177.0/http/server.ts";
import { createClient } from "https://esm.sh/@supabase/supabase-js@2";

const corsHeaders = {
  "Access-Control-Allow-Origin": "*",
  "Access-Control-Allow-Headers": "authorization, x-client-info, apikey, content-type",
};

interface EmailRecord {
  id: string;
  user_id: string;
  from_email: string;
  to_email: string;
  subject: string;
  body_text: string | null;
  body_html: string | null;
  metadata: Record<string, any> | null;
}

interface ProductInfo {
  id: string;
  name: string;
  brand: string | null;
  category: string | null;
  price: number;
  description: string | null;
  stock_quantity: number;
}

interface OrderInfo {
  id: string;
  order_number: string;
  status: string;
  total_amount: number;
  shipping_address: string | null;
  tracking_number: string | null;
  shipped_at: string | null;
  notes: string | null;
  created_at: string;
}

/**
 * 使用 Qwen 从邮件内容中提取订单号
 */
async function extractOrderNumber(
  subject: string,
  content: string
): Promise<string> {
  const QWEN_API_KEY = Deno.env.get("QWEN_API_KEY");
  const QWEN_BASE_URL = Deno.env.get("QWEN_BASE_URL") || "https://dashscope.aliyuncs.com/compatible-mode/v1";
  const QWEN_MODEL = Deno.env.get("QWEN_LLM_MODEL") || "qwen-max";

  if (!QWEN_API_KEY) {
    throw new Error("QWEN_API_KEY not configured");
  }

  const systemPrompt = `你是一个专业的订单号提取助手。请从邮件内容中提取订单号。
要求：
1. 只返回订单号本身，不要任何解释
2. 如果没有找到订单号，返回"无"
3. 订单号可能是纯数字、字母数字组合、UUID等格式`;

  const userPrompt = `请从以下邮件中提取订单号：

主题：${subject}
内容：${content}

请直接返回订单号，如果没有则返回"无"`;

  const result = await callQwenApi(QWEN_API_KEY, QWEN_BASE_URL, QWEN_MODEL, systemPrompt, userPrompt, 0.1, 100);
  return (result && result !== "无") ? result.trim() : "";
}

/**
 * 在订单表中搜索订单
 */
async function findOrder(
  supabaseClient: any,
  orderNumber: string
): Promise<OrderInfo | null> {
  const { data, error } = await supabaseClient
    .from("orders")
    .select("id, order_number, status, total_amount, shipping_address, tracking_number, shipped_at, notes, created_at")
    .eq("order_number", orderNumber)
    .maybeSingle();

  if (error || !data) return null;
  return data as OrderInfo;
}

/**
 * 根据邮箱查找用户的最新订单
 */
async function findLatestOrderByEmail(
  supabaseClient: any,
  emailAddress: string
): Promise<OrderInfo | null> {
  // 1. 通过 RPC 查找用户 ID
  const { data: userId } = await supabaseClient
    .rpc("get_user_id_by_email", { email_address: emailAddress })
    .maybeSingle();

  if (!userId) {
    console.log(`⚠️ [email-generate-replies] No user found for email: ${emailAddress}`);
    return null;
  }

  // 2. 查找该用户的最新订单
  const { data, error } = await supabaseClient
    .from("orders")
    .select("id, order_number, status, total_amount, shipping_address, tracking_number, shipped_at, notes, created_at")
    .eq("user_id", userId)
    .order("created_at", { ascending: false })
    .limit(1)
    .maybeSingle();

  if (error || !data) return null;
  return data as OrderInfo;
}

/**
 * 通用 Qwen API 调用
 */
async function callQwenApi(
  apiKey: string,
  baseUrl: string,
  model: string,
  systemPrompt: string,
  userPrompt: string,
  temperature: number = 0.7,
  maxTokens: number = 1500
): Promise<string> {
  let apiUrl: string;
  let requestBody: any;

  if (baseUrl.includes("/chat/completions")) {
    apiUrl = baseUrl;
    requestBody = {
      model,
      messages: [
        { role: "system", content: systemPrompt },
        { role: "user", content: userPrompt },
      ],
      temperature,
      max_tokens: maxTokens,
    };
  } else {
    const cleanUrl = baseUrl.replace(/\/+$/, "");
    if (cleanUrl.includes("/compatible-mode/v1")) {
      apiUrl = `${cleanUrl}/chat/completions`;
      requestBody = {
        model,
        messages: [
          { role: "system", content: systemPrompt },
          { role: "user", content: userPrompt },
        ],
        temperature,
        max_tokens: maxTokens,
      };
    } else {
      apiUrl = `${cleanUrl}/services/aigc/text-generation/generation`;
      requestBody = {
        model,
        input: {
          messages: [
            { role: "system", content: systemPrompt },
            { role: "user", content: userPrompt },
          ],
        },
        parameters: { temperature, max_tokens: maxTokens },
      };
    }
  }

  const response = await fetch(apiUrl, {
    method: "POST",
    headers: {
      Authorization: `Bearer ${apiKey}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify(requestBody),
  });

  if (!response.ok) {
    const errorText = await response.text();
    throw new Error(`Qwen API error: ${response.status} - ${errorText}`);
  }

  const result = await response.json();

  if (result.choices?.[0]?.message?.content) {
    return result.choices[0].message.content;
  } else if (result.output?.text) {
    return result.output.text;
  } else if (result.output?.choices?.[0]?.message?.content) {
    return result.output.choices[0].message.content;
  }
  return "";
}

/**
 * 使用 Qwen 从邮件内容中提取商品关键词
 */
async function extractProductKeywords(
  subject: string,
  content: string
): Promise<string[]> {
  const QWEN_API_KEY = Deno.env.get("QWEN_API_KEY");
  const QWEN_BASE_URL = Deno.env.get("QWEN_BASE_URL") || "https://dashscope.aliyuncs.com/compatible-mode/v1";
  const QWEN_MODEL = Deno.env.get("QWEN_LLM_MODEL") || "qwen-max";

  if (!QWEN_API_KEY) {
    throw new Error("QWEN_API_KEY not configured");
  }

  const systemPrompt = `你是一个专业的商品关键词提取助手。请从邮件内容中提取客户咨询的商品名称、品牌或型号。
要求：
1. 只返回关键词，用逗号分隔
2. 如果没有明确的商品信息，返回空
3. 优先提取具体的商品型号或名称`;

  const userPrompt = `请从以下邮件中提取商品关键词：

主题：${subject}
内容：${content}

请直接返回关键词（用逗号分隔），如果没有则返回"无"`;

  // 判断 API 路径格式
  let apiUrl: string;
  let requestBody: any;

  if (QWEN_BASE_URL.includes("/chat/completions")) {
    apiUrl = QWEN_BASE_URL;
    requestBody = {
      model: QWEN_MODEL,
      messages: [
        { role: "system", content: systemPrompt },
        { role: "user", content: userPrompt },
      ],
      temperature: 0.3,
      max_tokens: 200,
    };
  } else {
    const baseUrl = QWEN_BASE_URL.replace(/\/+$/, "");
    if (baseUrl.includes("/compatible-mode/v1")) {
      apiUrl = `${baseUrl}/chat/completions`;
      requestBody = {
        model: QWEN_MODEL,
        messages: [
          { role: "system", content: systemPrompt },
          { role: "user", content: userPrompt },
        ],
        temperature: 0.3,
        max_tokens: 200,
      };
    } else {
      apiUrl = `${baseUrl}/services/aigc/text-generation/generation`;
      requestBody = {
        model: QWEN_MODEL,
        input: {
          messages: [
            { role: "system", content: systemPrompt },
            { role: "user", content: userPrompt },
          ],
        },
        parameters: {
          temperature: 0.3,
          max_tokens: 200,
        },
      };
    }
  }

  const response = await fetch(apiUrl, {
    method: "POST",
    headers: {
      "Authorization": `Bearer ${QWEN_API_KEY}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify(requestBody),
  });

  if (!response.ok) {
    const errorText = await response.text();
    throw new Error(`Qwen API error: ${response.status} - ${errorText}`);
  }

  const result = await response.json();

  // 提取回复内容
  let replyContent = "";
  if (result.choices?.[0]?.message?.content) {
    replyContent = result.choices[0].message.content;
  } else if (result.output?.text) {
    replyContent = result.output.text;
  } else if (result.output?.choices?.[0]?.message?.content) {
    replyContent = result.output.choices[0].message.content;
  }

  if (!replyContent || replyContent === "无") {
    return [];
  }

  // 解析关键词
  return replyContent
    .split(/[,，、]/)
    .map((k: string) => k.trim())
    .filter((k: string) => k && k.length > 0);
}

/**
 * 在商品表中搜索匹配的商品
 */
async function searchProducts(
  supabaseClient: any,
  keywords: string[],
  limit: number = 3
): Promise<ProductInfo[]> {
  if (keywords.length === 0) {
    return [];
  }

  const products: ProductInfo[] = [];

  for (const keyword of keywords) {
    if (products.length >= limit) break;

    // 搜索商品名称、品牌、描述
    const { data, error } = await supabaseClient
      .from("products")
      .select("id, name, brand, category, price, description, stock_quantity")
      .or(`name.ilike.%${keyword}%,brand.ilike.%${keyword}%,description.ilike.%${keyword}%`)
      .eq("is_active", true)
      .limit(limit - products.length);

    if (!error && data) {
      for (const product of data) {
        // 去重
        if (!products.find((p) => p.id === product.id)) {
          products.push(product);
        }
      }
    }
  }

  return products.slice(0, limit);
}

/**
 * 调用 Qwen Chat API 生成回复
 */
async function generateReplyWithQwen(
  subject: string,
  content: string,
  senderEmail: string,
  productContext?: ProductInfo[],
  orderContext?: OrderInfo | null
): Promise<string> {
  const QWEN_API_KEY = Deno.env.get("QWEN_API_KEY");
  const QWEN_BASE_URL = Deno.env.get("QWEN_BASE_URL") || "https://dashscope.aliyuncs.com/compatible-mode/v1";
  const QWEN_MODEL = Deno.env.get("QWEN_LLM_MODEL") || "qwen-max";

  if (!QWEN_API_KEY) {
    throw new Error("QWEN_API_KEY not configured");
  }

  // 构建系统提示词
  let systemPrompt = `你是一个专业的电商客服，需要回复客户的邮件。要求：
1. 语气友好、专业
2. 针对邮件内容进行回应
3. 如果涉及订单或商品问题，表示会尽快处理
4. 如果是咨询类邮件，提供相关信息或引导
5. 回复内容要完整，包含称呼、正文、结束语`;

  // 如果有订单上下文，添加到系统提示词
  if (orderContext) {
    const statusLabels: Record<string, string> = {
      pending: "待处理",
      confirmed: "已确认",
      shipped: "已发货",
      delivered: "已送达",
      cancelled: "已取消",
    };
    const orderStatus = statusLabels[orderContext.status] || orderContext.status;

    systemPrompt += `\n\n以下是客户相关的订单信息，请在回复中参考：
- 订单编号：${orderContext.order_number}
- 订单状态：${orderStatus}
- 订单金额：¥${orderContext.total_amount}
- 收货地址：${orderContext.shipping_address || "未知"}
- 物流单号：${orderContext.tracking_number || "暂无"}
- 发货时间：${orderContext.shipped_at || "暂未发货"}
- 备注：${orderContext.notes || "无"}
- 下单时间：${orderContext.created_at}`;
  }

  // 如果有商品上下文，添加到系统提示词
  if (productContext && productContext.length > 0) {
    const productList = productContext
      .map(
        (p) =>
          `- ${p.name}（品牌：${p.brand || "未知"}，类别：${p.category || "未知"}，价格：¥${p.price}，库存：${p.stock_quantity}）`
      )
      .join("\n");

    systemPrompt += `\n\n以下是客户可能咨询的相关商品信息，请在回复中参考这些信息：
${productList}`;
  }

  const userPrompt = `请根据收到的邮件内容生成一封回复邮件。

邮件主题：${subject}
发件人：${senderEmail}
邮件内容：
${content}`;

  // 判断 API 路径格式
  let apiUrl: string;
  let requestBody: any;

  if (QWEN_BASE_URL.includes("/chat/completions")) {
    // OpenAI 兼容模式 - 直接使用完整 URL
    apiUrl = QWEN_BASE_URL;
    requestBody = {
      model: QWEN_MODEL,
      messages: [
        { role: "system", content: systemPrompt },
        { role: "user", content: userPrompt },
      ],
      temperature: 0.7,
      max_tokens: 1500,
    };
  } else {
    // 旧版 DashScope API - 拼接路径
    const baseUrl = QWEN_BASE_URL.replace(/\/+$/, "");
    if (baseUrl.includes("/compatible-mode/v1")) {
      // OpenAI 兼容模式基础 URL
      apiUrl = `${baseUrl}/chat/completions`;
      requestBody = {
        model: QWEN_MODEL,
        messages: [
          { role: "system", content: systemPrompt },
          { role: "user", content: userPrompt },
        ],
        temperature: 0.7,
        max_tokens: 1500,
      };
    } else {
      // 旧版 API
      apiUrl = `${baseUrl}/services/aigc/text-generation/generation`;
      requestBody = {
        model: QWEN_MODEL,
        input: {
          messages: [
            { role: "system", content: systemPrompt },
            { role: "user", content: userPrompt },
          ],
        },
        parameters: {
          temperature: 0.7,
          max_tokens: 1500,
        },
      };
    }
  }

  const response = await fetch(apiUrl, {
    method: "POST",
    headers: {
      "Authorization": `Bearer ${QWEN_API_KEY}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify(requestBody),
  });

  if (!response.ok) {
    const errorText = await response.text();
    throw new Error(`Qwen API error: ${response.status} - ${errorText}`);
  }

  const result = await response.json();

  // 提取回复内容 - 支持两种格式
  let replyContent = "";

  // OpenAI 兼容格式
  if (result.choices?.[0]?.message?.content) {
    replyContent = result.choices[0].message.content;
  }
  // 旧版 DashScope 格式
  else if (result.output?.text) {
    replyContent = result.output.text;
  }
  else if (result.output?.choices?.[0]?.message?.content) {
    replyContent = result.output.choices[0].message.content;
  }

  if (!replyContent) {
    throw new Error("No content in Qwen response");
  }

  return replyContent;
}

serve(async (req) => {
  // CORS
  if (req.method === "OPTIONS") {
    return new Response("ok", { headers: corsHeaders });
  }

  try {
    const supabaseClient = createClient(
      Deno.env.get("SUPABASE_URL") ?? "",
      Deno.env.get("SUPABASE_SERVICE_ROLE_KEY") ?? ""
    );

    // 查询收件箱中待处理的邮件（delivered + read，排除已生成回复的）
    const { data: pendingEmails, error: fetchError } = await supabaseClient
      .from("emails")
      .select("*")
      .in("status", ["delivered", "read"])
      .order("created_at", { ascending: true });

    if (fetchError) {
      throw fetchError;
    }

    if (!pendingEmails || pendingEmails.length === 0) {
      return new Response(
        JSON.stringify({
          message: "No pending emails to process",
          processed: 0,
          generated: 0,
          skipped: 0,
          failed: 0,
        }),
        {
          headers: { ...corsHeaders, "Content-Type": "application/json" },
          status: 200,
        }
      );
    }

    console.log(`📬 [email-generate-replies] Found ${pendingEmails.length} pending emails`);

    const results = {
      processed: 0,
      generated: 0,
      skipped: 0,
      failed: 0,
      details: [] as Array<{ email_id: string; status: string; error?: string }>,
    };

    for (const email of pendingEmails as EmailRecord[]) {
      results.processed++;

      try {
        // 原子性更新状态为 draft_replied，防止并发重复处理
        // 只有当状态还是 delivered 或 read 时才更新
        const { data: updatedData, error: updateError } = await supabaseClient
          .from("emails")
          .update({ status: "draft_replied" })
          .eq("id", email.id)
          .in("status", ["delivered", "read"])
          .select("id")
          .single();

        if (updateError || !updatedData) {
          console.log(`⏭️ [email-generate-replies] Email ${email.id} already being processed by another instance, skipping`);
          results.skipped++;
          results.details.push({ email_id: email.id, status: "skipped" });
          continue;
        }

        // 检查是否已有回复草稿（通过 metadata.reply_to_email_id）
        const { data: existingDraft } = await supabaseClient
          .from("emails")
          .select("id")
          .eq("status", "draft")
          .contains("metadata", { reply_to_email_id: email.id })
          .maybeSingle();

        if (existingDraft) {
          console.log(`⏭️ [email-generate-replies] Email ${email.id} already has a draft, skipping`);
          results.skipped++;
          results.details.push({ email_id: email.id, status: "skipped" });
          continue;
        }

        // 准备邮件内容
        const emailContent = email.body_text || email.body_html || "(无内容)";
        const subject = email.subject || "(无主题)";

        // 检查是否为商品咨询或订单相关邮件
        const emailCategory = email.metadata?.category;
        let productContext: ProductInfo[] | undefined;
        let orderContext: OrderInfo | null | undefined;

        // 商品咨询 → 提取商品关键词
        if (emailCategory === "product_inquiry") {
          console.log(`🔍 [email-generate-replies] Product inquiry detected for email ${email.id}, extracting keywords...`);

          try {
            const keywords = await extractProductKeywords(subject, emailContent);
            console.log(`📝 [email-generate-replies] Extracted keywords:`, keywords);

            if (keywords.length > 0) {
              productContext = await searchProducts(supabaseClient, keywords, 3);
              console.log(`🛍️ [email-generate-replies] Found ${productContext.length} matching products`);
            }
          } catch (extractError) {
            console.warn(`⚠️ [email-generate-replies] Failed to extract product keywords:`, extractError);
          }
        }

        // 订单相关 → 提取订单号并查找订单
        if (emailCategory && ["order_placed", "order_fulfillment", "delivery_receipt", "payment_notification", "abnormal_order"].includes(emailCategory)) {
          console.log(`📦 [email-generate-replies] Order-related email detected for email ${email.id}, extracting order number...`);

          try {
            const orderNumber = await extractOrderNumber(subject, emailContent);
            console.log(`🔢 [email-generate-replies] Extracted order number: "${orderNumber}"`);

            if (orderNumber) {
              orderContext = await findOrder(supabaseClient, orderNumber);
              if (orderContext) {
                console.log(`✅ [email-generate-replies] Found order: ${orderContext.order_number}, status: ${orderContext.status}`);
              } else {
                console.log(`⚠️ [email-generate-replies] Order not found for number: ${orderNumber}`);
              }
            }

            // 如果没有找到订单号或订单，根据发件人邮箱查找用户的最新订单
            if (!orderContext) {
              console.log(`🔍 [email-generate-replies] Looking up latest order for sender: ${email.from_email}`);
              orderContext = await findLatestOrderByEmail(supabaseClient, email.from_email);
              if (orderContext) {
                console.log(`✅ [email-generate-replies] Found latest order: ${orderContext.order_number}, status: ${orderContext.status}`);
              } else {
                console.log(`⚠️ [email-generate-replies] No orders found for sender: ${email.from_email}`);
              }
            }
          } catch (orderError) {
            console.warn(`⚠️ [email-generate-replies] Failed to extract order info:`, orderError);
          }
        }

        // 调用 Qwen API 生成回复
        console.log(`🤖 [email-generate-replies] Generating reply for email ${email.id}`);

        const replyContent = await generateReplyWithQwen(
          subject,
          emailContent,
          email.from_email,
          productContext,
          orderContext
        );

        // 生成回复主题
        const replySubject = subject.startsWith("Re:") ? subject : `Re: ${subject}`;

        // 创建草稿邮件
        const { error: insertError } = await supabaseClient.from("emails").insert({
          user_id: email.user_id,
          to_email: email.from_email,
          from_email: email.to_email,
          subject: replySubject,
          body_text: replyContent,
          body_html: replyContent.replace(/\n/g, "<br>"),
          status: "draft",
          in_reply_to: email.id,
          metadata: {
            reply_to_email_id: email.id,
            category: email.metadata?.category || "general",
            source: "ai_generated",
            original_subject: subject,
          },
        });

        if (insertError) {
          throw insertError;
        }

        console.log(`✅ [email-generate-replies] Generated draft for email ${email.id}`);
        results.generated++;
        results.details.push({ email_id: email.id, status: "generated" });

      } catch (error) {
        console.error(`❌ [email-generate-replies] Failed to process email ${email.id}:`, error);

        // 回滚状态，让下次调度可以重试
        const { error: rollbackError } = await supabaseClient
          .from("emails")
          .update({ status: email.status })
          .eq("id", email.id);

        if (rollbackError) {
          console.error(`❌ [email-generate-replies] Failed to rollback status for email ${email.id}:`, rollbackError);
        } else {
          console.log(`✅ [email-generate-replies] Rolled back status for email ${email.id}`);
        }

        results.failed++;
        results.details.push({
          email_id: email.id,
          status: "failed",
          error: error instanceof Error ? error.message : String(error),
        });
      }
    }

    return new Response(
      JSON.stringify({
        message: "Processing completed",
        ...results,
      }),
      {
        headers: { ...corsHeaders, "Content-Type": "application/json" },
        status: 200,
      }
    );

  } catch (error) {
    console.error("❌ [email-generate-replies] Fatal error:", error);
    return new Response(
      JSON.stringify({
        error: error instanceof Error ? error.message : String(error),
      }),
      {
        headers: { ...corsHeaders, "Content-Type": "application/json" },
        status: 500,
      }
    );
  }
});
