import { analyzePrompt } from "../services/openaiService.js";
import { createPost, getPostBySlug, listPosts } from "../services/blogService.js";
import { listDatasets } from "../services/datasetService.js";
import { getProjectsDirectory } from "../services/projectService.js";
import { getResearchRepository } from "../services/researchService.js";
import { askAiChatbot, streamAiChatbot, warmupAiChatbot } from "../services/aiChatbotService.js";
import {
  DIMENSION_KEYS,
  generateBridgeupCurrentPortrait,
  generateBridgeupDimension,
  generateBridgeupNextAction,
  getBridgeupSurveyConfig,
  warmupBridgeupModel,
} from "../services/bridgeupLegacyService.js";

function handleAsync(handler) {
  return async (req, res, next) => {
    try {
      await handler(req, res, next);
    } catch (error) {
      next(error);
    }
  };
}

export function registerApiRoutes(app) {
  app.get("/api/health", (req, res) => {
    res.json({
      status: "ok",
      service: "coldbrewnlp-be",
    });
  });

  app.post(
    "/api/ai-chatbot/message",
    handleAsync(async (req, res) => {
      const response = await askAiChatbot({
        message: req.body?.message,
        history: req.body?.history,
      });
      res.status(response.status).json(response.body);
    })
  );

  app.post(
    "/api/chat",
    handleAsync(async (req, res) => {
      const response = await askAiChatbot({
        message: req.body?.message,
        history: req.body?.history,
      });
      res.status(response.status).json(response.body);
    })
  );

  app.post(
    "/api/chat/stream",
    handleAsync(async (req, res) => {
      await streamAiChatbot({
        message: req.body?.message,
        history: req.body?.history,
        res,
      });
    })
  );

  app.get(
    "/api/chat/warmup",
    handleAsync(async (req, res) => {
      const result = await warmupAiChatbot();
      if (!result.ok) {
        return res.status(result.status || 503).json({ ok: false, warmed: false, message: result.message || "Warmup failed" });
      }
      res.json({ ok: true, warmed: true });
    })
  );

  app.post(
    "/api/analyze",
    handleAsync(async (req, res) => {
      const response = await analyzePrompt(req.body?.prompt);
      res.status(response.status).json(response.body);
    })
  );

  app.get(
    "/api/datasets",
    handleAsync(async (req, res) => {
      const datasets = await listDatasets();
      res.json(datasets);
    })
  );

  app.get(
    "/api/research",
    handleAsync(async (req, res) => {
      const research = await getResearchRepository();
      res.json(research);
    })
  );

  app.get(
    "/api/projects",
    handleAsync(async (req, res) => {
      const projects = await getProjectsDirectory();
      res.json(projects);
    })
  );

  app.get(
    "/api/bridgeup/survey-config",
    handleAsync(async (req, res) => {
      const config = await getBridgeupSurveyConfig();
      res.json(config);
    })
  );

  app.get(
    "/api/bridgeup/warmup",
    handleAsync(async (req, res) => {
      const result = await warmupBridgeupModel();
      if (!result.ok) {
        return res.status(503).json({ ok: false, warmed: false, message: result.message || "Warmup failed" });
      }
      res.json({ ok: true, warmed: true });
    })
  );
  app.post(
    "/api/bridgeup/recommendation",
    handleAsync(async (req, res) => {
      const [portraitResp, nextResp] = await Promise.all([
        generateBridgeupCurrentPortrait(req.body || {}),
        generateBridgeupNextAction(req.body || {}),
      ]);

      const portrait = portraitResp?.body?.data || "";
      const nextAction = nextResp?.body?.data || "";
      const combined = [
        portrait ? `Chân dung hiện tại: ${portrait}` : "",
        nextAction ? `Hành động tiếp theo: ${nextAction}` : "",
      ]
        .filter(Boolean)
        .join("\n\n");

      res.json({
        ok: true,
        provider: "bridgeup-legacy-compatible",
        result: combined || "Đã nhận dữ liệu khảo sát nhưng chưa tạo được kết quả phân tích.",
      });
    })
  );

  app.post(
    "/api/bridgeup/recommendation/current-portrait",
    handleAsync(async (req, res) => {
      const response = await generateBridgeupCurrentPortrait(req.body || {});
      res.status(response.status).json(response.body);
    })
  );

  app.post(
    "/api/bridgeup/recommendation/next-action",
    handleAsync(async (req, res) => {
      const response = await generateBridgeupNextAction(req.body || {});
      res.status(response.status).json(response.body);
    })
  );

  app.post(
    "/api/bridgeup/recommendation/dimension/:key",
    handleAsync(async (req, res) => {
      const key = req.params.key;
      if (!DIMENSION_KEYS.includes(key)) {
        return res.status(400).json({ ok: false, section: key, message: "Invalid dimension key" });
      }

      const response = await generateBridgeupDimension(req.body || {}, key);
      res.status(response.status).json(response.body);
    })
  );

  app.get(
    "/api/blog/posts",
    handleAsync(async (req, res) => {
      const posts = await listPosts();
      res.json(posts);
    })
  );

  app.get(
    "/api/blog/posts/:slug",
    handleAsync(async (req, res) => {
      const post = await getPostBySlug(req.params.slug);

      if (!post) {
        return res.status(404).json({ error: "Post not found." });
      }

      res.json(post);
    })
  );

  app.post(
    "/api/blog/posts",
    handleAsync(async (req, res) => {
      const response = await createPost(req.body);
      res.status(response.status).json(response.body);
    })
  );
}

