import OpenAI from "openai";
import { OPENAI_MODEL } from "../config.js";

const MODEL_TIMEOUT_MS = 20000;

function toNumber(value) {
  const n = Number(value);
  return Number.isFinite(n) ? n : 0;
}

function pickModelClient() {
  const hfEndpoint = process.env.HF_ENDPOINT;
  const hfModel = process.env.MODEL_ID;
  const hfToken = process.env.HF_TOKEN;

  if (hfEndpoint && hfModel && hfToken) {
    return {
      client: new OpenAI({
        baseURL: hfEndpoint,
        apiKey: hfToken,
      }),
      model: hfModel,
      provider: "hf-endpoint",
    };
  }

  if (process.env.OPENAI_API_KEY) {
    return {
      client: new OpenAI({ apiKey: process.env.OPENAI_API_KEY }),
      model: OPENAI_MODEL,
      provider: "openai",
    };
  }

  return null;
}

function createFallbackRecommendation(metrics, reason = "") {
  const lines = [];

  if (reason) {
    lines.push(`Khong the lay ket qua truc tiep tu model (${reason}). Day la goi y fallback.`);
  } else {
    lines.push("Ban chua cau hinh model, day la ket qua goi y tam thoi.");
  }

  if (metrics.healthScore < 50) {
    lines.push("Uu tien nang cap suc khoe: tap luyen deu 2-3 buoi/tuan va on dinh giac ngu.");
  }

  if (metrics.learningScore < 50) {
    lines.push("Tang toc hoc tap: dat muc toi thieu 4 gio/tuan va tham gia 1 khoa hoc ngan han.");
  }

  if (metrics.careerScore < 8) {
    lines.push("Career cap dang thap: de xuat xay dung lo trinh 90 ngay voi KPI nang luc ro rang.");
  }

  if (metrics.happinessScore < 6) {
    lines.push("Can bang hanh phuc: tang ket noi gia dinh, ban be va cac hoat dong xa hoi chat luong.");
  }

  if (metrics.contributionScore < 4) {
    lines.push("Nang cao dong gop: dat 1 muc tieu dong gop cong dong/thang co the do duoc.");
  }

  if (lines.length === 1) {
    lines.push("Tong the on dinh. Uu tien du tri ky luat hoc tap va theo doi tien do moi 2 tuan.");
  }

  return lines.join("\n");
}

function withTimeout(promise, timeoutMs) {
  return Promise.race([
    promise,
    new Promise((_, reject) => {
      setTimeout(() => reject(new Error(`Model timeout after ${timeoutMs}ms`)), timeoutMs);
    }),
  ]);
}

export async function generateBridgeupRecommendation(payload) {
  const scores = payload?.scores || {};
  const metrics = {
    totalScore: toNumber(payload?.metrics?.totalScore),
    careerScore: toNumber(payload?.metrics?.careerScore),
    healthScore: toNumber(payload?.metrics?.healthScore),
    learningScore: toNumber(payload?.metrics?.learningScore),
    happinessScore: toNumber(payload?.metrics?.happinessScore),
    contributionScore: toNumber(payload?.metrics?.contributionScore),
  };

  const modelTarget = pickModelClient();
  if (!modelTarget) {
    return {
      status: 200,
      body: {
        ok: true,
        provider: "fallback",
        result: createFallbackRecommendation(metrics),
      },
    };
  }

  const prompt = [
    "Ban la chuyen gia danh gia nang luc va phat trien ca nhan.",
    "Dua vao diem khao sat, hay tra ve ket qua bang tieng Viet, gon ro rang, co hanh dong cu the.",
    "Bo cuc bat buoc:",
    "1) Tong quan hien trang (3-4 cau).",
    "2) 3 uu tien hanh dong trong 30 ngay toi (danh sach danh so).",
    "3) 3 chi so theo doi tien bo (danh sach danh so).",
    "",
    `Tong diem: ${metrics.totalScore}`,
    `Career: ${metrics.careerScore}`,
    `Health: ${metrics.healthScore}`,
    `Learning: ${metrics.learningScore}`,
    `Happiness: ${metrics.happinessScore}`,
    `Contribution: ${metrics.contributionScore}`,
    "",
    `Chi tiet diem theo cau hoi: ${JSON.stringify(scores)}`,
  ].join("\n");

  try {
    const response = await withTimeout(
      modelTarget.client.responses.create({
        model: modelTarget.model,
        input: [
          {
            role: "system",
            content:
              "Ban la coach phat trien toan dien. Khong noi chung chung. Dua ra khuyen nghi kha thi va do luong duoc.",
          },
          {
            role: "user",
            content: prompt,
          },
        ],
        temperature: 0.4,
      }),
      MODEL_TIMEOUT_MS
    );

    return {
      status: 200,
      body: {
        ok: true,
        provider: modelTarget.provider,
        model: modelTarget.model,
        result: response.output_text || "Khong co noi dung tu model.",
      },
    };
  } catch (error) {
    return {
      status: 200,
      body: {
        ok: true,
        provider: "fallback-after-error",
        warning: error?.message || "Unknown model error",
        result: createFallbackRecommendation(metrics, error?.message || "model error"),
      },
    };
  }
}
