const MODULE_SCHEMAS = {
  deviation: {
    keys: ["severity", "actionTaken", "rootCause"],
    user:
      "Return a JSON object with keys: severity (one of: Low, Medium, High, Critical), actionTaken (string), rootCause (string).",
  },
  "case-investigation": {
    keys: [
      "lessonLearned",
      "rootCause",
      "fiveWhys",
      "immediateAction",
    ],
    user:
      "Return a JSON object with keys: lessonLearned, rootCause, fiveWhys, immediateAction (all strings).",
  },
  "site-monitoring": {
    keys: ["riskLevel", "correctiveAction", "priority"],
    user:
      "Return a JSON object with keys: riskLevel (Low, Medium, or High), correctiveAction (string), priority (Low, Medium, High, or Urgent).",
  },
  "risk-assessment": {
    keys: ["riskLevel", "controlMeasures", "residualRisk"],
    user:
      "Return a JSON object with keys: riskLevel (Low, Medium, High, or Critical), controlMeasures (string), residualRisk (Low, Medium, or High).",
  },
  jsa: {
    keys: ["hazards", "controls", "ppe"],
    user:
      "Return a JSON object with keys: hazards, controls, ppe (all strings).",
  },
  "minutes-of-meeting": {
    keys: ["actionItems", "decisions", "nextSteps"],
    user:
      "Return a JSON object with keys: actionItems, decisions, nextSteps (all strings).",
  },
  "permit-to-work": {
    keys: ["precautions", "ppe", "emergencyProcedure"],
    user:
      "Return a JSON object with keys: precautions, ppe, emergencyProcedure (all strings).",
  },
  hazop: {
    keys: ["deviation", "causes", "consequences", "safeguards"],
    user:
      "Return a JSON object with keys: deviation, causes, consequences, safeguards (strings; causes may summarize multiple causes in one string).",
  },
};

const SYSTEM_PROMPT =
  "You are a professional EHS (Environment, Health & Safety) assistant for NordSafe EHS. Analyze the provided description and return ONLY a valid JSON object with suggested field values. Be professional, concise, and accurate.";

const describe = async (req, res) => {
  const apiKey = process.env.OPENROUTER_API_KEY;
  if (!apiKey) {
    return res.status(503).json({
      success: false,
      message: "AI service is not configured (OPENROUTER_API_KEY).",
    });
  }

  const { description, moduleType } = req.body || {};
  if (
    typeof description !== "string" ||
    !description.trim() ||
    typeof moduleType !== "string"
  ) {
    return res.status(400).json({
      success: false,
      message: "description (non-empty string) and moduleType are required.",
    });
  }

  const schema = MODULE_SCHEMAS[moduleType];
  if (!schema) {
    return res.status(400).json({
      success: false,
      message: `Unknown moduleType: ${moduleType}`,
    });
  }

  const userContent = `${schema.user}\n\nDescription:\n${description.trim()}`;

  try {
    const response = await fetch("https://openrouter.ai/api/v1/chat/completions", {
      method: "POST",
      headers: {
        Authorization: `Bearer ${apiKey}`,
        "Content-Type": "application/json",
        "HTTP-Referer": process.env.OPENROUTER_HTTP_REFERER || "https://app.nordsafe-ehs.com",
        "X-Title": "NordSafe EHS",
      },
      body: JSON.stringify({
        model: "openai/gpt-3.5-turbo",
        messages: [
          { role: "system", content: SYSTEM_PROMPT },
          { role: "user", content: userContent },
        ],
        temperature: 0.3,
        max_tokens: 1024,
      }),
    });

    const data = await response.json();
    if (!response.ok) {
      console.error("OpenRouter error:", data);
      return res.status(502).json({
        success: false,
        message: data?.error?.message || "AI provider request failed.",
      });
    }

    const raw =
      data?.choices?.[0]?.message?.content ||
      data?.choices?.[0]?.text ||
      "";
    const jsonMatch = raw.match(/\{[\s\S]*\}/);
    if (!jsonMatch) {
      return res.status(422).json({
        success: false,
        message: "AI did not return valid JSON.",
        raw,
      });
    }

    let parsed;
    try {
      parsed = JSON.parse(jsonMatch[0]);
    } catch (e) {
      return res.status(422).json({
        success: false,
        message: "Failed to parse AI JSON.",
        raw,
      });
    }

    const suggestions = {};
    for (const key of schema.keys) {
      if (parsed[key] != null && String(parsed[key]).trim() !== "") {
        suggestions[key] = String(parsed[key]).trim();
      }
    }

    return res.json({ success: true, suggestions });
  } catch (err) {
    console.error("describe error:", err);
    return res.status(500).json({
      success: false,
      message: "Failed to generate suggestions.",
    });
  }
};

module.exports = { describe };
