import * as NodeServices from "@effect/platform-node/NodeServices";
import { it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as fsp from "node:fs/promises";
import * as nodePath from "node:path";
import { execFileSync } from "node:child_process";

import { discoverClaudeSkills } from "./ClaudeSkills.ts";

const ROOT = process.env.PERF_ROOT!;
import { appendFileSync } from "node:fs";
const out = (s: string) => appendFileSync(nodePath.join(ROOT, "results.txt"), s + "\n");
const median = (xs: number[]) => {
  const s = [...xs].sort((a, b) => a - b);
  return s[Math.floor(s.length / 2)]!;
};
const stats = (xs: number[]) =>
  `n=${xs.length} median=${median(xs).toFixed(1)}ms min=${Math.min(...xs).toFixed(1)} max=${Math.max(...xs).toFixed(1)}`;

async function buildFixture() {
  const configDir = nodePath.join(ROOT, "claude-home");
  const skill = async (dir: string, name: string) => {
    await fsp.mkdir(nodePath.join(dir, name), { recursive: true });
    await fsp.writeFile(
      nodePath.join(dir, name, "SKILL.md"),
      `---\nname: ${name}\ndescription: Skill ${name} for load testing.\n---\n\n# ${name}\n\n${"Body text. ".repeat(200)}\n`,
    );
  };
  for (let i = 0; i < 20; i++) await skill(nodePath.join(configDir, "skills"), `user-${i}`);
  const projects: string[] = [];
  for (let p = 0; p < 43; p++) {
    const dir = nodePath.join(ROOT, "projects", `wt-${p}`);
    await fsp.mkdir(dir, { recursive: true });
    execFileSync("git", ["init", "-q", dir]);
    for (let i = 0; i < 5; i++) await skill(nodePath.join(dir, ".claude", "skills"), `proj-${i}`);
    projects.push(dir);
  }
  const plugins: Record<string, unknown[]> = {};
  const enabled: Record<string, boolean> = {};
  for (let k = 0; k < 30; k++) {
    const install = nodePath.join(configDir, "plugins", "cache", "market", `plugin-${k}`, "1.0.0");
    await fsp.mkdir(nodePath.join(install, ".claude-plugin"), { recursive: true });
    await fsp.writeFile(
      nodePath.join(install, ".claude-plugin", "plugin.json"),
      JSON.stringify({ name: `plugin-${k}` }),
    );
    for (let i = 0; i < 6; i++) await skill(nodePath.join(install, "skills"), `s${i}`);
    const records: unknown[] = [];
    for (let r = 0; r < 20; r++) {
      records.push({ scope: "project", projectPath: projects[r % 20], installPath: install });
    }
    records.push({ scope: "user", installPath: install });
    plugins[`plugin-${k}@market`] = records;
    enabled[`plugin-${k}@market`] = true;
  }
  await fsp.writeFile(
    nodePath.join(configDir, "plugins", "installed_plugins.json"),
    JSON.stringify({ version: 2, plugins }),
  );
  await fsp.writeFile(
    nodePath.join(configDir, "settings.json"),
    JSON.stringify({ enabledPlugins: enabled }),
  );
  return { configDir, projects };
}

it.layer(NodeServices.layer)("perf 47611", (it) => {
  it.effect(
    "measure discovery",
    () =>
      Effect.gen(function* () {
        const { configDir, projects } = yield* Effect.promise(buildFixture);
        const env = { CLAUDE_CONFIG_DIR: configDir, HOME: ROOT };
        const realFs = yield* FileSystem.FileSystem;
        let calls = 0;
        const countingFs = new Proxy(realFs, {
          get(target, key, receiver) {
            const value = Reflect.get(target, key, receiver);
            if (typeof value !== "function") return value;
            return (...args: unknown[]) => {
              calls++;
              return (value as (...a: unknown[]) => unknown).apply(target, args);
            };
          },
        });
        const discover = (cwd: string, fs: FileSystem.FileSystem = realFs) =>
          discoverClaudeSkills({ homePath: "" }, cwd, env).pipe(
            Effect.provideService(FileSystem.FileSystem, fs),
          );

        const first = yield* discover(projects[0]!);
        out(`skills found per discovery: ${first.length}`);
        calls = 0;
        yield* discover(projects[0]!, countingFs);
        out(`FileSystem calls per discovery: ${calls}`);

        for (let w = 0; w < 5; w++) yield* discover(projects[w % 43]!);
        const single: number[] = [];
        for (let i = 0; i < 30; i++) {
          const t = performance.now();
          yield* discover(projects[i % 43]!);
          single.push(performance.now() - t);
        }
        out(`single discovery: ${stats(single)}`);

        const perCall: number[] = [];
        const wall: number[] = [];
        for (let round = 0; round < 10; round++) {
          const t0 = performance.now();
          const times = yield* Effect.all(
            projects.map((cwd) =>
              Effect.gen(function* () {
                const t = performance.now();
                yield* discover(cwd);
                return performance.now() - t;
              }),
            ),
            { concurrency: "unbounded" },
          );
          wall.push(performance.now() - t0);
          perCall.push(median(times));
        }
        out(`43 concurrent, median per-call latency per round: ${stats(perCall)}`);
        out(`43 concurrent, wall time per round: ${stats(wall)}`);

        const prompt = "Please refactor the session store and add tests.";
        const pattern =
          /(^|\s)\p{Sc}(?![0-9][0-9_]*(?:[kKmMbBtT]|[eE][0-9]+)?(?:\s|$))(?=[a-zA-Z0-9:_-]*[a-zA-Z])([a-zA-Z0-9][a-zA-Z0-9:_-]*)(?=\s|$)/u;
        const t = performance.now();
        for (let i = 0; i < 10000; i++) pattern.test(prompt);
        out(`mention regex test: ${((performance.now() - t) / 10000 * 1000).toFixed(3)}us per prompt`);
      }),
    120000,
  );
});
