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

interface ParetoPoint {
  fw: string;
  model: string;
  tier: string;
  score: number;
  cost: string;
  costNum: number;
  optimal: boolean;
}

// Cost per task by model (from generate_sample_results.py MODEL_PROFILES)
const MODEL_COSTS: Record<string, number> = {
  "claude-opus-4.5": 0.58,
  "claude-sonnet-4.5": 0.42,
  "gpt-5": 0.55,
  "gpt-4.1": 0.34,
  "gpt-4o": 0.29,
  "claude-haiku-4.5": 0.09,
  "gpt-4.1-mini": 0.07,
  "deepseek-v3": 0.03,
  "llama-4-maverick": 0.02,
  "qwen-3.5": 0.02,
};

const MODEL_TIERS: 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",
};

function computePareto(points: ParetoPoint[]): Set<string> {
  // Sort by cost ascending, then score descending
  const sorted = [...points].sort((a, b) => a.costNum - b.costNum || b.score - a.score);
  const frontier = new Set<string>();
  let bestScore = -Infinity;

  for (const p of sorted) {
    if (p.score > bestScore) {
      frontier.add(`${p.fw}:${p.model}`);
      bestScore = p.score;
    }
  }
  return frontier;
}

function loadParetoData(): ParetoPoint[] {
  const resultsDir = path.join(process.cwd(), "..", "data", "results");

  try {
    if (fs.existsSync(resultsDir)) {
      const files = fs.readdirSync(resultsDir).filter((f) => f.endsWith(".json") && f !== "skills-gain.json");
      const points: ParetoPoint[] = [];

      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") continue;

        const model = parsed.model as string;
        const costNum = MODEL_COSTS[model] ?? 0.10;
        points.push({
          fw: parsed.framework,
          model,
          tier: MODEL_TIERS[model] || "Other",
          score: parsed.overall,
          cost: `$${costNum.toFixed(2)}`,
          costNum,
          optimal: false, // computed below
        });
      }

      if (points.length > 0) {
        const frontier = computePareto(points);
        for (const p of points) {
          p.optimal = frontier.has(`${p.fw}:${p.model}`);
        }
        // Sort by score descending
        points.sort((a, b) => b.score - a.score);
        return points;
      }
    }
  } catch {
    // Fall through to sample data
  }

  // Fallback sample data
  return [
    { fw: "OpenClaw", model: "claude-sonnet-4.5", tier: "Flagship", score: 92.1, cost: "$0.58", costNum: 0.58, optimal: true },
    { fw: "OpenClaw", model: "gpt-4.1", tier: "Flagship", score: 89.5, cost: "$0.51", costNum: 0.51, optimal: true },
    { fw: "IronClaw", model: "claude-sonnet-4.5", tier: "Flagship", score: 90.3, cost: "$0.55", costNum: 0.55, optimal: false },
    { fw: "IronClaw", model: "claude-sonnet-4-20250514", tier: "Standard", score: 85.7, cost: "$0.34", costNum: 0.34, optimal: true },
    { fw: "QClaw", model: "gpt-4o", tier: "Standard", score: 82.5, cost: "$0.29", costNum: 0.29, optimal: true },
    { fw: "ZeroClaw", model: "claude-haiku-4.5", tier: "Economy", score: 72.8, cost: "$0.09", costNum: 0.09, optimal: true },
    { fw: "NullClaw", model: "gpt-4.1-mini", tier: "Economy", score: 70.2, cost: "$0.07", costNum: 0.07, optimal: true },
    { fw: "PicoClaw", model: "claude-sonnet-4-20250514", tier: "Standard", score: 78.4, cost: "$0.32", costNum: 0.32, optimal: false },
    { fw: "NanoBot", model: "deepseek-v3", tier: "Open Source", score: 68.5, cost: "$0.03", costNum: 0.03, optimal: true },
    { fw: "NanoBot", model: "llama-4-maverick", tier: "Open Source", score: 63.4, cost: "$0.02", costNum: 0.02, optimal: false },
    { fw: "OpenClaw", model: "deepseek-v3", tier: "Open Source", score: 71.3, cost: "$0.04", costNum: 0.04, optimal: false },
  ];
}

export default function ParetoPage() {
  const dataPoints = loadParetoData();
  const frontierCount = dataPoints.filter((p) => p.optimal).length;

  return (
    <>
      <header className="page-header">
        <h1>Cost-Performance Pareto Frontier</h1>
        <p>
          Visualize the trade-off between benchmark score and inference cost
          across Claw framework-model pairs. Points on the Pareto frontier represent
          configurations where no other option is both cheaper and higher-scoring.
        </p>
      </header>

      <div
        style={{
          display: "grid",
          gridTemplateColumns: "repeat(auto-fit, minmax(160px, 1fr))",
          gap: "1rem",
          marginBottom: "1.5rem",
        }}
      >
        {[
          { label: "Total Configurations", value: String(dataPoints.length), sub: "framework-model pairs" },
          { label: "Pareto Optimal", value: String(frontierCount), sub: "frontier points" },
          {
            label: "Best Score",
            value: Math.max(...dataPoints.map((p) => p.score)).toFixed(1),
            sub: dataPoints.reduce((best, p) => (p.score > best.score ? p : best)).fw,
          },
          {
            label: "Cheapest Optimal",
            value: dataPoints
              .filter((p) => p.optimal)
              .reduce((best, p) => (p.costNum < best.costNum ? p : best)).cost,
            sub: dataPoints
              .filter((p) => p.optimal)
              .reduce((best, p) => (p.costNum < best.costNum ? p : best)).fw,
          },
        ].map((stat) => (
          <div key={stat.label} className="card" style={{ textAlign: "center" }}>
            <div
              style={{
                fontSize: "0.75rem",
                textTransform: "uppercase",
                letterSpacing: "0.05em",
                color: "var(--text-secondary)",
                marginBottom: "0.25rem",
              }}
            >
              {stat.label}
            </div>
            <div style={{ fontSize: "1.5rem", fontWeight: 700 }}>{stat.value}</div>
            <div style={{ fontSize: "0.8rem", color: "var(--text-secondary)", marginTop: "0.15rem" }}>
              {stat.sub}
            </div>
          </div>
        ))}
      </div>

      <div className="card">
        <div className="placeholder" style={{ flexDirection: "column", gap: "1rem" }}>
          <div>
            <strong style={{ fontSize: "1.1rem" }}>D3.js Scatter Plot</strong>
          </div>
          <div style={{ maxWidth: "500px", lineHeight: 1.7 }}>
            <p>This page will render an interactive scatter plot:</p>
            <ul
              style={{
                textAlign: "left",
                marginTop: "0.75rem",
                listStyle: "disc inside",
                fontSize: "0.85rem",
              }}
            >
              <li>
                <strong>X-axis:</strong> Inference cost per task (USD)
              </li>
              <li>
                <strong>Y-axis:</strong> Overall benchmark score
              </li>
              <li>
                <strong>Points:</strong> Each Claw framework-model combination
              </li>
              <li>
                <strong>Color:</strong> Model tier (Flagship / Standard / Economy / Open Source)
              </li>
              <li>
                <strong>Frontier line:</strong> Pareto-optimal configurations
                highlighted
              </li>
              <li>
                <strong>Hover:</strong> Tooltip with detailed breakdown
              </li>
            </ul>
          </div>
        </div>
      </div>

      <div
        className="card"
        style={{ marginTop: "1.5rem" }}
      >
        <h3
          style={{
            fontSize: "0.95rem",
            fontWeight: 600,
            marginBottom: "0.75rem",
          }}
        >
          Claw Ecosystem Data Points
        </h3>
        <div className="table-wrap">
          <table>
            <thead>
              <tr>
                <th>Framework</th>
                <th>Model</th>
                <th>Tier</th>
                <th>Score</th>
                <th>Cost / Task</th>
                <th>Pareto Optimal</th>
              </tr>
            </thead>
            <tbody>
              {dataPoints.map((row) => (
                <tr key={`${row.fw}-${row.model}`}>
                  <td style={{ fontWeight: 600 }}>{row.fw}</td>
                  <td>
                    <code style={{ fontFamily: "var(--font-mono)", fontSize: "0.8rem" }}>
                      {row.model}
                    </code>
                  </td>
                  <td style={{ fontSize: "0.8rem" }}>{row.tier}</td>
                  <td>{row.score.toFixed(1)}</td>
                  <td style={{ fontFamily: "var(--font-mono)" }}>{row.cost}</td>
                  <td>
                    {row.optimal ? (
                      <span className="score score-high">Yes</span>
                    ) : (
                      <span
                        style={{
                          color: "var(--text-secondary)",
                          fontSize: "0.85rem",
                        }}
                      >
                        No
                      </span>
                    )}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </>
  );
}
