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

/* ------------------------------------------------------------------ */
/*  Types                                                              */
/* ------------------------------------------------------------------ */

interface AgentProfileData {
  profileId: string;
  displayName: string;
  model: string;
  framework: string;
  skillsMode: string;
  skills: string[];
  mcpServers: string[];
  memoryModules: string[];
  modelTier: string | null;
  tags: Record<string, string>;
}

interface ProgressiveData {
  baseline_pass_rate: number;
  current_pass_rate: number;
  absolute_gain: number;
  normalized_gain: number;
  gain_by_domain?: Record<string, { baseline: number; current: number; gain: number }>;
}

interface BenchResult {
  framework: string;
  model: string;
  overall: number;
  taskCompletion: number;
  efficiency: number;
  security: number;
  skills: number;
  ux: number;
  testTier?: string | null;
  agentProfile?: AgentProfileData | null;
  progressive?: ProgressiveData | null;
}

type WeightProfile = "general" | "security" | "performance";

// These must match PRESET_PROFILES in src/claw_bench/core/scorer.py
const WEIGHT_PROFILES: Record<
  WeightProfile,
  { label: string; weights: Record<string, number> }
> = {
  general: {
    label: "General",
    weights: {
      taskCompletion: 0.40,
      efficiency: 0.20,
      security: 0.15,
      skills: 0.15,
      ux: 0.10,
    },
  },
  security: {
    label: "Security-first",
    weights: {
      taskCompletion: 0.25,
      efficiency: 0.10,
      security: 0.40,
      skills: 0.15,
      ux: 0.10,
    },
  },
  performance: {
    label: "Performance-first",
    weights: {
      taskCompletion: 0.30,
      efficiency: 0.35,
      security: 0.10,
      skills: 0.15,
      ux: 0.10,
    },
  },
};

/* ------------------------------------------------------------------ */
/*  Data loading                                                       */
/* ------------------------------------------------------------------ */

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

  // Try to load real results from data/results/*.json
  try {
    if (fs.existsSync(resultsDir)) {
      const files = fs
        .readdirSync(resultsDir)
        .filter((f) => f.endsWith(".json"));

      if (files.length > 0) {
        const all = files.flatMap((file) => {
          const raw = fs.readFileSync(path.join(resultsDir, file), "utf-8");
          const parsed = JSON.parse(raw);
          return Array.isArray(parsed) ? parsed : [parsed];
        });
        // Filter to entries that have all required BenchResult fields
        const valid = all.filter(
          (r: Record<string, unknown>) =>
            r.framework && r.model && typeof r.overall === "number" && typeof r.taskCompletion === "number"
        );
        if (valid.length > 0) return valid as BenchResult[];
      }
    }
  } catch {
    // Fall through to sample data
  }

  // Sample data reflecting the Claw ecosystem (placeholder until real benchmarks run)
  return [
    {
      framework: "OpenClaw",
      model: "gpt-4.1",
      overall: 82.4,
      taskCompletion: 88.3,
      efficiency: 74.5,
      security: 72.1,
      skills: 91.2,
      ux: 80.8,
      testTier: "comprehensive",
      agentProfile: {
        profileId: "a1b2c3",
        displayName: "OpenClaw / gpt-4.1 (+2 skills, 1 MCP)",
        model: "gpt-4.1",
        framework: "OpenClaw",
        skillsMode: "curated",
        skills: ["calendar.md", "code-review.md"],
        mcpServers: ["filesystem"],
        memoryModules: [],
        modelTier: "flagship",
        tags: {},
      },
      progressive: {
        baseline_pass_rate: 0.72,
        current_pass_rate: 0.88,
        absolute_gain: 0.16,
        normalized_gain: 0.571,
      },
    },
    {
      framework: "OpenClaw",
      model: "claude-sonnet-4.5",
      overall: 84.1,
      taskCompletion: 90.1,
      efficiency: 76.2,
      security: 73.5,
      skills: 89.7,
      ux: 82.3,
      testTier: "comprehensive",
      agentProfile: {
        profileId: "d4e5f6",
        displayName: "OpenClaw / claude-sonnet-4.5 (+3 skills, 2 MCP)",
        model: "claude-sonnet-4.5",
        framework: "OpenClaw",
        skillsMode: "curated",
        skills: ["calendar.md", "code-review.md", "file-ops.md"],
        mcpServers: ["filesystem", "github"],
        memoryModules: [],
        modelTier: "flagship",
        tags: {},
      },
      progressive: {
        baseline_pass_rate: 0.65,
        current_pass_rate: 0.82,
        absolute_gain: 0.17,
        normalized_gain: 0.486,
      },
    },
    {
      framework: "IronClaw",
      model: "gpt-4.1",
      overall: 79.8,
      taskCompletion: 81.5,
      efficiency: 78.9,
      security: 94.2,
      skills: 62.3,
      ux: 76.1,
      testTier: "comprehensive",
      agentProfile: {
        profileId: "g7h8i9",
        displayName: "IronClaw / gpt-4.1",
        model: "gpt-4.1",
        framework: "IronClaw",
        skillsMode: "vanilla",
        skills: [],
        mcpServers: [],
        memoryModules: [],
        modelTier: "flagship",
        tags: {},
      },
    },
    {
      framework: "ZeroClaw",
      model: "claude-sonnet-4.5",
      overall: 71.3,
      taskCompletion: 74.2,
      efficiency: 96.8,
      security: 68.5,
      skills: 45.1,
      ux: 69.4,
      testTier: "quick",
      agentProfile: {
        profileId: "j1k2l3",
        displayName: "ZeroClaw / claude-sonnet-4.5",
        model: "claude-sonnet-4.5",
        framework: "ZeroClaw",
        skillsMode: "vanilla",
        skills: [],
        mcpServers: [],
        memoryModules: [],
        modelTier: "flagship",
        tags: {},
      },
    },
    {
      framework: "NullClaw",
      model: "gpt-4.1-mini",
      overall: 65.7,
      taskCompletion: 68.9,
      efficiency: 98.2,
      security: 61.3,
      skills: 38.5,
      ux: 58.2,
      testTier: "track",
      agentProfile: {
        profileId: "m4n5o6",
        displayName: "NullClaw / gpt-4.1-mini",
        model: "gpt-4.1-mini",
        framework: "NullClaw",
        skillsMode: "vanilla",
        skills: [],
        mcpServers: [],
        memoryModules: [],
        modelTier: "economy",
        tags: {},
      },
    },
    {
      framework: "PicoClaw",
      model: "gemini-3-flash",
      overall: 62.1,
      taskCompletion: 65.4,
      efficiency: 92.1,
      security: 55.8,
      skills: 41.2,
      ux: 54.7,
      testTier: "comprehensive",
      agentProfile: {
        profileId: "p7q8r9",
        displayName: "PicoClaw / gemini-3-flash (+1 skill)",
        model: "gemini-3-flash",
        framework: "PicoClaw",
        skillsMode: "curated",
        skills: ["file-ops.md"],
        mcpServers: [],
        memoryModules: [],
        modelTier: "economy",
        tags: {},
      },
      progressive: {
        baseline_pass_rate: 0.58,
        current_pass_rate: 0.65,
        absolute_gain: 0.07,
        normalized_gain: 0.167,
      },
    },
    {
      framework: "NanoBot",
      model: "qwen-3.5",
      overall: 58.9,
      taskCompletion: 62.1,
      efficiency: 85.3,
      security: 50.2,
      skills: 35.8,
      ux: 60.1,
      testTier: "quick",
      agentProfile: {
        profileId: "s1t2u3",
        displayName: "NanoBot / qwen-3.5",
        model: "qwen-3.5",
        framework: "NanoBot",
        skillsMode: "vanilla",
        skills: [],
        mcpServers: [],
        memoryModules: [],
        modelTier: "opensource",
        tags: {},
      },
    },
    {
      framework: "QClaw",
      model: "gpt-4.1",
      overall: 80.2,
      taskCompletion: 86.7,
      efficiency: 73.1,
      security: 70.4,
      skills: 88.5,
      ux: 78.9,
      testTier: "comprehensive",
      agentProfile: {
        profileId: "v4w5x6",
        displayName: "QClaw / gpt-4.1 (+1 MCP, 1 mem)",
        model: "gpt-4.1",
        framework: "QClaw",
        skillsMode: "native",
        skills: [],
        mcpServers: ["github"],
        memoryModules: ["conversation-buffer"],
        modelTier: "flagship",
        tags: {},
      },
      progressive: {
        baseline_pass_rate: 0.70,
        current_pass_rate: 0.80,
        absolute_gain: 0.10,
        normalized_gain: 0.333,
      },
    },
  ];
}

/* ------------------------------------------------------------------ */
/*  Helpers                                                            */
/* ------------------------------------------------------------------ */

function scoreClass(score: number): string {
  if (score >= 85) return "score score-high";
  if (score >= 70) return "score score-mid";
  return "score score-low";
}

/* ------------------------------------------------------------------ */
/*  Page                                                               */
/* ------------------------------------------------------------------ */

/** Dedup results by profileId — keep the entry with the highest overall score. */
function dedupByProfile(results: BenchResult[]): BenchResult[] {
  const best = new Map<string, BenchResult>();
  for (const r of results) {
    const key = r.agentProfile?.profileId ?? `${r.framework}:${r.model}`;
    const existing = best.get(key);
    if (!existing || r.overall > existing.overall) {
      best.set(key, r);
    }
  }
  return Array.from(best.values());
}

export default function LeaderboardPage() {
  const results = loadResults();

  // Dedup by profile and sort by overall descending
  const sorted = dedupByProfile(results).sort((a, b) => b.overall - a.overall);

  return (
    <>
      <header className="page-header">
        <h1>Claw Bench Leaderboard</h1>
        <p>
          Standardized evaluation of AI Agent frameworks across 210 tasks,
          14 domains, and 4 difficulty levels.
        </p>
        <div
          style={{
            marginTop: "1rem",
            display: "flex",
            gap: "0.75rem",
            flexWrap: "wrap",
          }}
        >
          <a
            href="/getting-started"
            style={{
              display: "inline-block",
              padding: "0.5rem 1.25rem",
              background: "var(--accent)",
              color: "#fff",
              borderRadius: "6px",
              textDecoration: "none",
              fontWeight: 600,
              fontSize: "0.9rem",
            }}
          >
            Run Benchmark
          </a>
          <a
            href="/profiles"
            style={{
              display: "inline-block",
              padding: "0.5rem 1.25rem",
              border: "1px solid var(--border)",
              borderRadius: "6px",
              textDecoration: "none",
              fontWeight: 600,
              fontSize: "0.9rem",
              color: "var(--text-primary)",
            }}
          >
            Agent Profiles
          </a>
          <a
            href="/skill.md"
            style={{
              display: "inline-block",
              padding: "0.5rem 1.25rem",
              border: "1px solid var(--border)",
              borderRadius: "6px",
              textDecoration: "none",
              fontWeight: 600,
              fontSize: "0.9rem",
              color: "var(--text-primary)",
            }}
          >
            skill.md (for AI agents)
          </a>
        </div>
      </header>

      <section style={{ marginBottom: "1.5rem" }}>
        <div
          style={{
            fontSize: "0.8rem",
            fontWeight: 600,
            textTransform: "uppercase" as const,
            letterSpacing: "0.05em",
            color: "var(--text-secondary)",
            marginBottom: "0.5rem",
          }}
        >
          Weight Profile
        </div>
        <div className="weight-selector">
          {Object.entries(WEIGHT_PROFILES).map(([key, profile]) => (
            <button
              key={key}
              className={key === "general" ? "active" : ""}
              title={`Weights: ${Object.entries(profile.weights)
                .map(([k, v]) => `${k}: ${(v * 100).toFixed(0)}%`)
                .join(", ")}`}
            >
              {profile.label}
            </button>
          ))}
        </div>
        <p
          style={{
            fontSize: "0.75rem",
            color: "var(--text-secondary)",
            fontStyle: "italic",
          }}
        >
          Weight profile switching requires client-side JS (coming soon). Scores
          shown use the General profile.
        </p>
      </section>

      <div className="card" style={{ padding: 0, overflow: "hidden" }}>
        <div className="table-wrap">
          <table>
            <thead>
              <tr>
                <th style={{ width: "4rem" }}>Rank</th>
                <th>Agent</th>
                <th>Tier</th>
                <th>Overall</th>
                <th>Gain</th>
                <th>Task Completion</th>
                <th>Efficiency</th>
                <th>Security</th>
                <th>Skills</th>
                <th>UX</th>
              </tr>
            </thead>
            <tbody>
              {sorted.map((row, i) => {
                const rank = i + 1;
                const rankClass =
                  rank <= 3 ? `rank rank-${rank}` : "rank";
                const displayName = row.agentProfile?.displayName ?? `${row.framework} / ${row.model}`;
                const gain = row.progressive?.absolute_gain;
                const tierLabel = row.testTier ?? "-";
                return (
                  <tr key={`${row.framework}-${row.model}-${row.agentProfile?.profileId ?? i}`}>
                    <td className={rankClass}>{rank}</td>
                    <td style={{ fontWeight: 600 }}>
                      {displayName}
                    </td>
                    <td>
                      <code
                        style={{
                          fontSize: "0.75rem",
                          fontFamily: "var(--font-mono)",
                          background: "var(--bg-secondary)",
                          padding: "0.15rem 0.4rem",
                          borderRadius: "4px",
                        }}
                      >
                        {tierLabel}
                      </code>
                    </td>
                    <td>
                      <span className={scoreClass(row.overall)}>
                        {row.overall.toFixed(1)}
                      </span>
                    </td>
                    <td>
                      {gain != null ? (
                        <span
                          style={{
                            color: gain >= 0 ? "var(--color-green, #22c55e)" : "var(--color-red, #ef4444)",
                            fontWeight: 600,
                            fontSize: "0.85rem",
                          }}
                        >
                          {gain >= 0 ? "+" : ""}
                          {(gain * 100).toFixed(1)}%
                        </span>
                      ) : (
                        <span style={{ color: "var(--text-secondary)", fontSize: "0.8rem" }}>-</span>
                      )}
                    </td>
                    <td>
                      <span className={scoreClass(row.taskCompletion)}>
                        {row.taskCompletion.toFixed(1)}
                      </span>
                    </td>
                    <td>
                      <span className={scoreClass(row.efficiency)}>
                        {row.efficiency.toFixed(1)}
                      </span>
                    </td>
                    <td>
                      <span className={scoreClass(row.security)}>
                        {row.security.toFixed(1)}
                      </span>
                    </td>
                    <td>
                      <span className={scoreClass(row.skills)}>
                        {row.skills.toFixed(1)}
                      </span>
                    </td>
                    <td>
                      <span className={scoreClass(row.ux)}>
                        {row.ux.toFixed(1)}
                      </span>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      </div>

      <footer
        style={{
          marginTop: "3rem",
          paddingBottom: "2rem",
          textAlign: "center",
          fontSize: "0.8rem",
          color: "var(--text-secondary)",
        }}
      >
        Sample data shown. Run benchmarks to populate real results in{" "}
        <code style={{ fontFamily: "var(--font-mono)" }}>data/results/</code>.
      </footer>
    </>
  );
}
