import fs from "node:fs";
import path from "node:path";

interface MatrixEntry {
  framework: string;
  model: string;
  overall: number;
}

function loadMatrix(): {
  frameworks: string[];
  modelTiers: { name: string; models: string[] }[];
  scores: Record<string, Record<string, number | null>>;
} {
  const resultsDir = path.join(process.cwd(), "..", "data", "results");
  const entries: MatrixEntry[] = [];

  try {
    if (fs.existsSync(resultsDir)) {
      const files = fs.readdirSync(resultsDir).filter((f) => f.endsWith(".json") && f !== "skills-gain.json");
      for (const file of files) {
        const raw = fs.readFileSync(path.join(resultsDir, file), "utf-8");
        const parsed = JSON.parse(raw);
        if (parsed.framework && parsed.model && typeof parsed.overall === "number") {
          entries.push({
            framework: parsed.framework,
            model: parsed.model,
            overall: parsed.overall,
          });
        }
      }
    }
  } catch {
    // Fall through to sample data
  }

  if (entries.length > 0) {
    // Build matrix from loaded data
    const fwSet = new Set<string>();
    const modelSet = new Set<string>();
    const scores: Record<string, Record<string, number | null>> = {};

    for (const e of entries) {
      fwSet.add(e.framework);
      modelSet.add(e.model);
      if (!scores[e.framework]) scores[e.framework] = {};
      scores[e.framework][e.model] = e.overall;
    }

    const frameworks = Array.from(fwSet).sort();
    const models = Array.from(modelSet).sort();

    // Fill null for untested combinations
    for (const fw of frameworks) {
      for (const m of models) {
        if (scores[fw][m] === undefined) scores[fw][m] = null;
      }
    }

    // Group models by tier based on known tier mappings
    const tierMap: Record<string, string> = {
      "claude-opus-4.5": "Flagship", "claude-sonnet-4.5": "Flagship",
      "gpt-5": "Flagship", "gpt-4.1": "Standard", "gpt-4o": "Standard",
      "claude-haiku-4.5": "Economy", "gpt-4.1-mini": "Economy",
      "deepseek-v3": "Open Source", "llama-4-maverick": "Open Source",
      "qwen-3.5": "Open Source",
    };
    const tierOrder = ["Flagship", "Standard", "Economy", "Open Source"];
    const tierGroups: Record<string, string[]> = {};
    for (const t of tierOrder) tierGroups[t] = [];
    for (const m of models) {
      const tier = tierMap[m] || "Other";
      if (!tierGroups[tier]) tierGroups[tier] = [];
      tierGroups[tier].push(m);
    }

    const modelTiers = tierOrder
      .filter((t) => tierGroups[t].length > 0)
      .map((t) => ({ name: t, models: tierGroups[t] }));

    // Add "Other" tier if any unrecognized models exist
    if (tierGroups["Other"]?.length > 0) {
      modelTiers.push({ name: "Other", models: tierGroups["Other"] });
    }

    return { frameworks, modelTiers, scores };
  }

  // Fallback sample data
  const frameworks = ["OpenClaw", "IronClaw", "ZeroClaw", "NullClaw", "PicoClaw", "NanoBot", "QClaw"];
  const modelTiers = [
    { name: "Flagship", models: ["claude-sonnet-4.5", "gpt-4.1"] },
    { name: "Standard", models: ["claude-sonnet-4-20250514", "gpt-4o"] },
    { name: "Economy", models: ["claude-haiku-4.5", "gpt-4.1-mini"] },
    { name: "Open Source", models: ["deepseek-v3", "llama-4-maverick"] },
  ];
  const scores: Record<string, Record<string, number | null>> = {
    OpenClaw: { "claude-sonnet-4.5": 92.1, "gpt-4.1": 89.5, "claude-sonnet-4-20250514": 87.4, "gpt-4o": 84.2, "claude-haiku-4.5": 78.3, "gpt-4.1-mini": 76.1, "deepseek-v3": 71.3, "llama-4-maverick": 68.9 },
    IronClaw: { "claude-sonnet-4.5": 90.3, "gpt-4.1": 88.1, "claude-sonnet-4-20250514": 85.7, "gpt-4o": 83.6, "claude-haiku-4.5": 76.9, "gpt-4.1-mini": 74.8, "deepseek-v3": 69.4, "llama-4-maverick": 67.2 },
    ZeroClaw: { "claude-sonnet-4.5": 86.2, "gpt-4.1": 84.0, "claude-sonnet-4-20250514": 80.5, "gpt-4o": 79.3, "claude-haiku-4.5": 72.8, "gpt-4.1-mini": 70.5, "deepseek-v3": 72.8, "llama-4-maverick": null },
    NullClaw: { "claude-sonnet-4.5": 85.0, "gpt-4.1": 83.7, "claude-sonnet-4-20250514": 80.1, "gpt-4o": 78.9, "claude-haiku-4.5": 71.5, "gpt-4.1-mini": 70.2, "deepseek-v3": null, "llama-4-maverick": 65.1 },
    PicoClaw: { "claude-sonnet-4.5": 83.8, "gpt-4.1": 81.2, "claude-sonnet-4-20250514": 78.4, "gpt-4o": 76.5, "claude-haiku-4.5": 69.7, "gpt-4.1-mini": 67.3, "deepseek-v3": null, "llama-4-maverick": null },
    NanoBot: { "claude-sonnet-4.5": 81.5, "gpt-4.1": 79.8, "claude-sonnet-4-20250514": 76.8, "gpt-4o": 74.0, "claude-haiku-4.5": 67.2, "gpt-4.1-mini": 65.8, "deepseek-v3": 68.5, "llama-4-maverick": 63.4 },
    QClaw: { "claude-sonnet-4.5": 88.9, "gpt-4.1": 87.1, "claude-sonnet-4-20250514": 84.3, "gpt-4o": 82.5, "claude-haiku-4.5": 75.6, "gpt-4.1-mini": 73.9, "deepseek-v3": 70.1, "llama-4-maverick": 66.8 },
  };
  return { frameworks, modelTiers, scores };
}

export default function MatrixPage() {
  const { frameworks, modelTiers, scores } = loadMatrix();
  const allModelColumns = modelTiers.flatMap((tier) => tier.models);

  function cellColor(score: number | null): string {
    if (score === null) return "var(--bg-secondary)";
    if (score >= 85) return "var(--success)";
    if (score >= 75) return "var(--warning)";
    return "var(--danger)";
  }

  function cellOpacity(score: number | null): number {
    if (score === null) return 0.3;
    return 0.4 + ((score - 60) / 40) * 0.6;
  }

  return (
    <>
      <header className="page-header">
        <h1>Compatibility Matrix</h1>
        <p>
          Claw framework x model tier heatmap showing overall benchmark scores across all
          tested combinations. Models are grouped by tier: Flagship, Standard, Economy, and Open Source.
        </p>
      </header>

      <div className="card" style={{ padding: 0, overflow: "hidden" }}>
        <div className="table-wrap">
          <table>
            <thead>
              <tr>
                <th
                  rowSpan={2}
                  style={{ position: "sticky", left: 0, background: "var(--bg-card)", zIndex: 2, verticalAlign: "bottom" }}
                >
                  Framework \ Model
                </th>
                {modelTiers.map((tier) => (
                  <th
                    key={tier.name}
                    colSpan={tier.models.length}
                    style={{
                      textAlign: "center",
                      fontSize: "0.75rem",
                      fontWeight: 700,
                      borderBottom: "2px solid var(--border)",
                    }}
                  >
                    {tier.name}
                  </th>
                ))}
              </tr>
              <tr>
                {allModelColumns.map((model) => (
                  <th key={model} style={{ textAlign: "center", fontSize: "0.65rem", fontWeight: 500 }}>
                    {model}
                  </th>
                ))}
              </tr>
            </thead>
            <tbody>
              {frameworks.map((fw) => (
                <tr key={fw}>
                  <td
                    style={{
                      fontWeight: 600,
                      position: "sticky",
                      left: 0,
                      background: "var(--bg-card)",
                      zIndex: 1,
                    }}
                  >
                    {fw}
                  </td>
                  {allModelColumns.map((model) => {
                    const score = scores[fw]?.[model] ?? null;
                    return (
                      <td
                        key={model}
                        style={{
                          textAlign: "center",
                          fontFamily: "var(--font-mono)",
                          fontSize: "0.85rem",
                          fontWeight: 600,
                          color: score !== null ? "#fff" : "var(--text-secondary)",
                          background: cellColor(score),
                          opacity: cellOpacity(score),
                        }}
                      >
                        {score !== null ? score.toFixed(1) : "--"}
                      </td>
                    );
                  })}
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      <div
        style={{
          display: "flex",
          gap: "1rem",
          marginTop: "1rem",
          fontSize: "0.75rem",
          color: "var(--text-secondary)",
          alignItems: "center",
          flexWrap: "wrap",
        }}
      >
        <span>Legend:</span>
        <span style={{ display: "flex", alignItems: "center", gap: "0.3rem" }}>
          <span
            style={{
              display: "inline-block",
              width: "12px",
              height: "12px",
              borderRadius: "2px",
              background: "var(--success)",
            }}
          />
          85+
        </span>
        <span style={{ display: "flex", alignItems: "center", gap: "0.3rem" }}>
          <span
            style={{
              display: "inline-block",
              width: "12px",
              height: "12px",
              borderRadius: "2px",
              background: "var(--warning)",
            }}
          />
          75-84
        </span>
        <span style={{ display: "flex", alignItems: "center", gap: "0.3rem" }}>
          <span
            style={{
              display: "inline-block",
              width: "12px",
              height: "12px",
              borderRadius: "2px",
              background: "var(--danger)",
            }}
          />
          &lt;75
        </span>
        <span style={{ display: "flex", alignItems: "center", gap: "0.3rem" }}>
          <span
            style={{
              display: "inline-block",
              width: "12px",
              height: "12px",
              borderRadius: "2px",
              background: "var(--bg-secondary)",
              border: "1px solid var(--border)",
            }}
          />
          Not tested
        </span>
      </div>
    </>
  );
}
