import { mkdir, stat, writeFile } from "node:fs/promises";
import { homedir } from "node:os";
import path from "node:path";
import type { CommandModule } from "yargs";
import type { GlobalArgv } from "../context.js";
import { details, dim, green, handle, printResult } from "../output.js";

type Args = GlobalArgv & Record<string, unknown>;

const SKILL_NAME = "freestyle-docs";

/**
 * Where the docs publish the skill. `FREESTYLE_DOCS_ORIGIN` exists for the
 * tests, which serve the file from a local server; there is no flag because
 * nobody has a second docs site.
 */
const DOCS_ORIGIN = process.env.FREESTYLE_DOCS_ORIGIN ?? "https://www.freestyle.sh";
const ONBOARD_URL = `${DOCS_ORIGIN}/docs/onboard.md`;

/**
 * onboard.md embeds the skill between these markers, for a reader that has to
 * copy it by hand. Doing that mechanically is the whole of this command, so it
 * reads the page agents are already pointed at rather than asking the docs for
 * an endpoint of its own.
 *
 * Anchored to a line of its own: the page also names the markers in prose,
 * a few lines above the body they delimit.
 */
const SKILL_BLOCK = /^<<<SKILL$\r?\n([^]*?)\r?\n^SKILL>>>$/m;

/**
 * One row per agent the installer knows. `detectDirs` is what the agent
 * leaves behind once it has run — its config directory — and `skillsDir` is
 * where it reads skills from. The two differ for Codex, which reads the
 * shared `.agents/skills` directory rather than one of its own.
 */
interface AgentTarget {
  id: string;
  label: string;
  detectDirs: string[];
  skillsDir: string;
}

const AGENTS: AgentTarget[] = [
  {
    id: "claude",
    label: "Claude Code",
    detectDirs: [".claude"],
    skillsDir: path.join(".claude", "skills"),
  },
  {
    id: "codex",
    label: "Codex",
    detectDirs: [".codex", ".agents"],
    skillsDir: path.join(".agents", "skills"),
  },
  {
    id: "copilot",
    label: "GitHub Copilot",
    detectDirs: [".copilot"],
    skillsDir: path.join(".copilot", "skills"),
  },
];

async function isDirectory(candidate: string): Promise<boolean> {
  try {
    return (await stat(candidate)).isDirectory();
  } catch {
    return false;
  }
}

async function fileExists(candidate: string): Promise<boolean> {
  try {
    return (await stat(candidate)).isFile();
  } catch {
    return false;
  }
}

/**
 * The skill body onboard.md publishes, verbatim. The frontmatter check keeps a
 * captive portal or an error page from being installed as a skill: whatever
 * comes back has to declare itself as this skill before it is written
 * anywhere.
 */
async function fetchSkill(): Promise<string> {
  let response: Response;
  try {
    response = await fetch(ONBOARD_URL, { headers: { accept: "text/markdown" } });
  } catch (error) {
    const reason = error instanceof Error ? (error.cause ?? error) : error;
    throw new Error(
      `Could not reach ${ONBOARD_URL} (${String(reason)}). Check your network and retry.`,
    );
  }
  if (!response.ok) {
    throw new Error(`Fetching ${ONBOARD_URL} failed with HTTP ${response.status}.`);
  }

  const body = SKILL_BLOCK.exec(await response.text())?.[1];
  if (!body || !new RegExp(`^---\\r?\\n[^]*?\\bname: ${SKILL_NAME}\\b`).test(body)) {
    throw new Error(
      `${ONBOARD_URL} did not carry the ${SKILL_NAME} skill. Nothing was written; open it and install by hand.`,
    );
  }
  return `${body}\n`;
}

/** `/Users/me/.claude/…` → `~/.claude/…`, for the pretty listing only. */
function displayPath(file: string): string {
  const home = homedir();
  return file.startsWith(`${home}${path.sep}`) ? `~${file.slice(home.length)}` : file;
}

const install: CommandModule<Args, Args> = {
  command: "install",
  describe: `Fetch the ${SKILL_NAME} skill and write it into each agent's skills directory`,
  builder: (y) =>
    y
      .option("agent", {
        type: "string",
        array: true,
        choices: AGENTS.map((agent) => agent.id),
        describe: "install for these agents only (default: every agent detected on this machine)",
      })
      .option("project", {
        type: "boolean",
        default: false,
        describe: "install into this project (./.claude/skills, …) instead of your home directory",
      })
      .option("print", {
        type: "boolean",
        default: false,
        describe: "print the skill to stdout instead of installing it",
      }),
  handler: handle(async (argv) => {
    const body = await fetchSkill();

    if (argv.print) {
      process.stdout.write(body);
      return;
    }

    const base = argv.project ? process.cwd() : homedir();
    let targets: AgentTarget[];
    if (argv.agent) {
      const ids = argv.agent as string[];
      targets = AGENTS.filter((agent) => ids.includes(agent.id));
    } else {
      const detections = await Promise.all(
        AGENTS.map(async (agent) => {
          const marks = await Promise.all(
            agent.detectDirs.map((dir) => isDirectory(path.join(base, dir))),
          );
          return marks.some(Boolean);
        }),
      );
      targets = AGENTS.filter((_, index) => detections[index]);
    }

    if (targets.length === 0) {
      throw new Error(
        `No agent directories found in ${base}. Pass --agent (${AGENTS.map((a) => a.id).join(", ")}) to pick one, or install by hand: ${ONBOARD_URL}`,
      );
    }

    const installed: Array<{ agent: string; label: string; path: string; updated: boolean }> = [];
    for (const target of targets) {
      const file = path.join(base, target.skillsDir, SKILL_NAME, "SKILL.md");
      const updated = await fileExists(file);
      await mkdir(path.dirname(file), { recursive: true });
      await writeFile(file, body);
      installed.push({ agent: target.id, label: target.label, path: file, updated });
    }

    printResult(argv, { skill: SKILL_NAME, source: ONBOARD_URL, installed }, ({ installed: rows }) =>
      [
        `${green("✓")} Installed the ${SKILL_NAME} skill.`,
        details(
          rows.map((row) => [
            row.label,
            row.updated ? `${displayPath(row.path)} ${dim("(updated)")}` : displayPath(row.path),
          ]),
        ),
        dim("Start a new agent session to pick it up."),
      ].join("\n\n"),
    );
  }),
};

/**
 * The docs skill, installed. The one command here that talks to the docs
 * site rather than the API: it takes no login, because it is how an agent
 * onboards before it has one.
 */
export const skillCommand: CommandModule<Args, Args> = {
  command: "skill <action>",
  describe: `Install the Freestyle docs as an agent skill (${SKILL_NAME})`,
  builder: (y) => y.command(install).demandCommand(1),
  handler: () => {},
};
