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;
}

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

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

  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];
        });
        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 with agent profiles
  return [
    {
      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: "abc123",
        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: "OpenClaw",
      model: "claude-sonnet-4.5",
      overall: 78.3,
      taskCompletion: 82.5,
      efficiency: 76.2,
      security: 73.5,
      skills: 72.1,
      ux: 78.0,
      testTier: "comprehensive",
      agentProfile: {
        profileId: "def456",
        displayName: "OpenClaw / claude-sonnet-4.5",
        model: "claude-sonnet-4.5",
        framework: "OpenClaw",
        skillsMode: "vanilla",
        skills: [],
        mcpServers: [],
        memoryModules: [],
        modelTier: "flagship",
        tags: {},
      },
    },
    {
      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: "ghi789",
        displayName: "IronClaw / gpt-4.1",
        model: "gpt-4.1",
        framework: "IronClaw",
        skillsMode: "vanilla",
        skills: [],
        mcpServers: [],
        memoryModules: [],
        modelTier: "flagship",
        tags: {},
      },
    },
  ];
}

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

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

/** Group results by a key extracted from each result. */
function groupBy<T>(items: T[], keyFn: (item: T) => string): Record<string, T[]> {
  const groups: Record<string, T[]> = {};
  for (const item of items) {
    const key = keyFn(item);
    if (!groups[key]) groups[key] = [];
    groups[key].push(item);
  }
  return groups;
}

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

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

  // Group by model to show progressive improvement
  const byModel = groupBy(results, (r) => r.model);
  // Group by framework
  const byFramework = groupBy(results, (r) => r.framework);

  return (
    <>
      <header className="page-header">
        <h1>Agent Profiles</h1>
        <p>
          Compare agent configurations across models and frameworks. See how
          adding skills, MCP servers, and memory modules progressively improves
          scores.
        </p>
        <div style={{ marginTop: "1rem" }}>
          <a
            href="/"
            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)",
            }}
          >
            Back to Leaderboard
          </a>
        </div>
      </header>

      {/* Group by Model */}
      <section style={{ marginBottom: "2rem" }}>
        <h2 style={{ fontSize: "1.25rem", marginBottom: "1rem" }}>
          By Model
        </h2>
        <p
          style={{
            fontSize: "0.85rem",
            color: "var(--text-secondary)",
            marginBottom: "1rem",
          }}
        >
          Same model, different skills/MCP configurations — see how each change
          affects the score.
        </p>

        {Object.entries(byModel)
          .sort(([a], [b]) => a.localeCompare(b))
          .map(([model, entries]) => (
            <div
              key={model}
              className="card"
              style={{ marginBottom: "1.5rem", padding: "1rem", overflow: "hidden" }}
            >
              <h3
                style={{
                  fontSize: "1rem",
                  marginBottom: "0.75rem",
                  fontFamily: "var(--font-mono)",
                }}
              >
                {model}
              </h3>
              <div className="table-wrap">
                <table>
                  <thead>
                    <tr>
                      <th>Agent</th>
                      <th>Skills Mode</th>
                      <th>MCP</th>
                      <th>Overall</th>
                      <th>Gain</th>
                      <th>Task Compl.</th>
                      <th>Efficiency</th>
                      <th>Security</th>
                    </tr>
                  </thead>
                  <tbody>
                    {entries
                      .sort((a, b) => b.overall - a.overall)
                      .map((row, idx) => {
                        const displayName =
                          row.agentProfile?.displayName ??
                          `${row.framework} / ${row.model}`;
                        const gain = row.progressive?.absolute_gain;
                        const mcpCount =
                          row.agentProfile?.mcpServers?.length ?? 0;
                        return (
                          <tr key={`${model}-${idx}`}>
                            <td style={{ fontWeight: 600 }}>{displayName}</td>
                            <td>
                              <code
                                style={{
                                  fontSize: "0.75rem",
                                  background: "var(--bg-secondary)",
                                  padding: "0.1rem 0.3rem",
                                  borderRadius: "3px",
                                }}
                              >
                                {row.agentProfile?.skillsMode ?? "vanilla"}
                              </code>
                            </td>
                            <td>{mcpCount > 0 ? mcpCount : "-"}</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,
                                  }}
                                >
                                  {gain >= 0 ? "+" : ""}
                                  {(gain * 100).toFixed(1)}%
                                </span>
                              ) : (
                                <span
                                  style={{
                                    color: "var(--text-secondary)",
                                    fontSize: "0.8rem",
                                  }}
                                >
                                  baseline
                                </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>
                          </tr>
                        );
                      })}
                  </tbody>
                </table>
              </div>
            </div>
          ))}
      </section>

      {/* Group by Framework */}
      <section style={{ marginBottom: "2rem" }}>
        <h2 style={{ fontSize: "1.25rem", marginBottom: "1rem" }}>
          By Framework
        </h2>
        <p
          style={{
            fontSize: "0.85rem",
            color: "var(--text-secondary)",
            marginBottom: "1rem",
          }}
        >
          Same framework, different models — compare model performance within
          each framework.
        </p>

        {Object.entries(byFramework)
          .sort(([a], [b]) => a.localeCompare(b))
          .map(([framework, entries]) => (
            <div
              key={framework}
              className="card"
              style={{ marginBottom: "1.5rem", padding: "1rem", overflow: "hidden" }}
            >
              <h3 style={{ fontSize: "1rem", marginBottom: "0.75rem" }}>
                {framework}
              </h3>
              <div className="table-wrap">
                <table>
                  <thead>
                    <tr>
                      <th>Model</th>
                      <th>Skills Mode</th>
                      <th>Tier</th>
                      <th>Overall</th>
                      <th>Task Completion</th>
                      <th>Efficiency</th>
                    </tr>
                  </thead>
                  <tbody>
                    {entries
                      .sort((a, b) => b.overall - a.overall)
                      .map((row, idx) => (
                        <tr key={`${framework}-${idx}`}>
                          <td>
                            <code
                              style={{
                                fontSize: "0.8rem",
                                fontFamily: "var(--font-mono)",
                              }}
                            >
                              {row.model}
                            </code>
                          </td>
                          <td>
                            {row.agentProfile?.skillsMode ?? "vanilla"}
                          </td>
                          <td>{row.testTier ?? "-"}</td>
                          <td>
                            <span className={scoreClass(row.overall)}>
                              {row.overall.toFixed(1)}
                            </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>
                        </tr>
                      ))}
                  </tbody>
                </table>
              </div>
            </div>
          ))}
      </section>

      {/* Radar Chart placeholder */}
      <section style={{ marginBottom: "2rem" }}>
        <div
          className="card"
          style={{
            padding: "2rem",
            textAlign: "center",
            color: "var(--text-secondary)",
          }}
        >
          <h3 style={{ fontSize: "1rem", marginBottom: "0.5rem" }}>
            Radar Chart Comparison
          </h3>
          <p style={{ fontSize: "0.85rem" }}>
            Interactive radar chart comparing 5-dimension scores across profiles
            (requires client-side JS — coming soon).
          </p>
        </div>
      </section>

      <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>
    </>
  );
}
