// Git for the sessions plugin: what a turn changed in its project's repository, and a session's commit. Git runs
// through the host's `processes` (AD-27), never with the worker's own `child_process`; nothing is written to its stdin
// (the host's guard never closes it). Paths are relative to the repository's top folder, `/`-separated, as git prints
// them. A folder outside any repository, or without git, has no state: `undefined`.
import { createHash } from 'node:crypto';
import { isAbsolute, join, relative, sep } from 'node:path';
import type { Context } from 'cordis';
import { cutText } from './text.ts';

export type Run = (
  cwd: string,
  args: string[],
) => Promise<{ code: number | null; stdout: string; stderr: string }>;

/** `git <args>` in `cwd`, through the host's processes, owned by `owner`. */
export const runner =
  (owner: Context): Run =>
  async (cwd, args) => {
    const child = await owner.processes.spawn(owner, {
      command: 'git',
      args,
      cwd,
      env: { GIT_TERMINAL_PROMPT: '0', GIT_OPTIONAL_LOCKS: '0' },
    });
    let stdout = '';
    let stderr = '';
    child.onOutput((stream, chunk) => {
      if (stream === 'stdout') stdout += chunk;
      else stderr += chunk;
    });
    const { code } = await child.exited;
    return { code, stdout, stderr };
  };

/** How long `ssh -G` may take to name an alias's host before the remote is read as written. */
export const SSH_RESOLVE_MS = 5000;

/** The host name ssh connects to for `alias` (`ssh -G`, which reads `~/.ssh/config` and connects nowhere), run in
 *  `cwd` through the host's processes; `undefined` when ssh fails or has not answered within `timeoutMs`. */
export const sshHostname = async (owner: Context, cwd: string, alias: string, timeoutMs = SSH_RESOLVE_MS) => {
  try {
    const child = await owner.processes.spawn(owner, { command: 'ssh', args: ['-G', alias], cwd });
    let stdout = '';
    child.onOutput((stream, chunk) => {
      if (stream === 'stdout') stdout += chunk;
    });
    let timer: ReturnType<typeof setTimeout> | undefined;
    const late = new Promise<'late'>((done) => {
      timer = setTimeout(() => done('late'), timeoutMs);
    });
    const end = await Promise.race([child.exited, late]);
    clearTimeout(timer);
    if (end === 'late') {
      void child.kill();
      return undefined;
    }
    return end.code === 0 ? /^hostname (\S+)$/m.exec(stdout)?.[1] : undefined;
  } catch {
    return undefined;
  }
};

/** `remote` with its ssh host alias replaced by the host `hostOf` resolves it to (`sshHostname`): a remote
 *  `git@github-work:o/r.git` whose `~/.ssh/config` says `HostName github.com` reads as GitHub's (plugins#114). Any other
 *  form (https, a path) and GitHub's own hosts come back as they are. */
export const resolveRemote = async (
  remote: string,
  hostOf: (alias: string) => Promise<string | undefined>,
) => {
  const found =
    /^(ssh:\/\/(?:[^@/]+@)?)([^/:@]+)(?::\d+)?\//i.exec(remote) ?? /^((?:[^@/:]+@)?)([^/:@]+):(?!\/)/.exec(remote);
  const alias = found?.[2];
  // A name only, never an option for ssh (`-…`).
  if (!found || !alias || !/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(alias) || /^(?:ssh\.)?github\.com$/i.test(alias))
    return remote;
  const host = await hostOf(alias);
  return host ? `${found[1]}${host}${remote.slice(found[1]!.length + alias.length)}` : remote;
};

/** The branches of the repository at `folder` that have a folder, as git lists them (`git worktree list`): its own
 *  checkout first, then each worktree under its `.worktrees/` (research-083). A folder's name is never read as a branch's
 *  name (`feat/x` and `feat-x` share one). */
export const worktreesOf = async (run: Run, folder: string) => {
  const { code, stdout } = await run(folder, ['worktree', 'list', '--porcelain']);
  if (code !== 0) return [];
  const all = stdout.split('\n\n').flatMap((block) => {
    const path = /^worktree (.+)$/m.exec(block)?.[1];
    const name = /^branch refs\/heads\/(.+)$/m.exec(block)?.[1];
    return path && name ? [{ name, folder: path }] : [];
  });
  const main = /^worktree (.+)$/m.exec(stdout)?.[1];
  return all.filter(
    (each) => each.folder === main || each.folder.startsWith(`${main}/.worktrees/`),
  );
};

/** A branch name from a message (research-083): its first words, lowercase, joined by `-`; empty when it has none.
 *  A URL gives none of them (plugins#73). The fallback of a model's name (`typedBranch`). */
export const branchSlug = (text: string) =>
  text
    .replace(/\b[a-z][a-z0-9+.-]*:\/\/\S*/gi, ' ')
    .toLowerCase()
    .normalize('NFKD')
    .replace(/[\u0300-\u036f'’]/g, '')
    .split(/[^a-z0-9]+/)
    .filter(Boolean)
    .slice(0, 6)
    // Whole words within 40 characters (a single longer word cut).
    .reduce(
      (name, word) =>
        !name ? word.slice(0, 40) : name.length + 1 + word.length <= 40 ? `${name}-${word}` : name,
      '',
    );

/** The example of the prompt that asks a model for a branch name: never taken as its answer (plugins#110). */
export const BRANCH_EXAMPLE = 'fix/e2e-shards';

/** A model's answer as a `type/topic` branch name (`fix/login-timeout`), `undefined` when it is not one or is the prompt's
 *  own example (a model echoing it would name every branch the same). */
export const typedBranch = (answer: string) => {
  // Its first line: a model may go on after the name (plugins#84).
  const name = (answer.trim().split('\n')[0] ?? '').trim().replace(/^`+|`+$/g, '');
  return name.length <= 40 &&
    /^(feat|fix|chore|ci|docs|refactor|test)\/[a-z0-9]+(-[a-z0-9]+)*$/.test(name) &&
    name !== BRANCH_EXAMPLE
    ? name
    : undefined;
};

/** `name`, else `name-2`, `name-3`…: the first that no branch of the repository at `folder` has. Each read as its full
 *  name, not git's short form (`heads/<name>` beside a tag of the same name: plugins#198). */
export const freeBranch = async (run: Run, folder: string, name: string) => {
  const { stdout } = await run(folder, ['branch', '--list', '--format=%(refname:lstrip=2)']);
  const taken = new Set(stdout.split('\n'));
  let free = name;
  for (let n = 2; taken.has(free); n++) free = `${name}-${n}`;
  return free;
};

/** The repository holding `cwd`: its top folder, and `cwd`'s path in it (`prefix`, `''` or ending with `/`); `undefined`
 *  outside one. */
export const repositoryAt = async (run: Run, cwd: string): Promise<Repository | undefined> => {
  const { code, stdout } = await run(cwd, ['rev-parse', '--show-toplevel', '--show-prefix']);
  const [top, prefix = ''] = stdout.split('\n');
  return code === 0 && top ? { top, prefix } : undefined;
};
export interface Repository {
  top: string;
  prefix: string;
}

/** Past this size a file's fingerprint is its size and mtime, not its content: a turn's snapshot never reads a huge file
 *  whole (#112). ponytail: an edit of such a file that keeps both is not seen. */
const HASH_MAX = 16 * 1024 * 1024;
/** A snapshot reads (stat and content) this many files at most, in `git status`'s order (tracked changes first): a
 *  folder of thousands of untracked files (a `node_modules` not ignored) costs no more (#121). The others are `unread`:
 *  one that appears or goes is still a change. ponytail: an edit of an unread file is not seen. */
const READ_MAX = 2_000;

/** The files of `top` that differ (read as `owner`) from `HEAD` (untracked ones included, ignored ones not), each with a fingerprint of
 *  its content now (`deleted` when gone): two states compared give what changed between them. */
export const stateOf = async (
  owner: Context,
  run: Run,
  top: string,
  { hashMax = HASH_MAX, readMax = READ_MAX }: { hashMax?: number; readMax?: number } = {},
) => {
  const { code, stdout } = await run(top, [
    'status',
    '--porcelain=v1',
    '-z',
    '--untracked-files=all',
    // A rename (`git mv`) is its deletion and its addition: both paths are the session's, so both get committed.
    '--no-renames',
  ]);
  if (code !== 0) return undefined;
  const paths = stdout
    .split('\0')
    .filter((field) => field.length >= 4)
    .map((field) => field.slice(3));
  const state = new Map<string, string>();
  await Promise.all(
    paths
      .slice(0, readMax)
      .map(async (path) => state.set(path, await fingerprint(owner, join(top, path), hashMax))),
  );
  for (const path of paths.slice(readMax)) state.set(path, 'unread');
  return state;
};

/** Read through the host (`ctx.fs`) as `owner`. */
const fingerprint = async (owner: Context, file: string, hashMax: number) => {
  try {
    const info = await owner.fs.stat(owner, file);
    if (!info) return 'deleted';
    if (!info.isFile) return `other:${info.mtimeMs}`;
    // Never a SHA-1: a file that crosses the limit during a turn shows as changed.
    if (info.size > hashMax) return `meta:${info.size}:${info.mtimeMs}`;
    return createHash('sha1')
      .update(await owner.fs.readFile(owner, file))
      .digest('hex');
  } catch {
    return 'deleted';
  }
};

/** The paths whose fingerprint differs between `before` and `after`. An `unread` file's content is unknown: in both
 *  states and gone from neither, it is no change (a path that entered before the cap pushed it past, #121). */
export const changed = (before: Map<string, string>, after: Map<string, string>) =>
  [...new Set([...before.keys(), ...after.keys()])].filter((path) => {
    const was = before.get(path);
    const now = after.get(path);
    const unknown =
      (was === 'unread' || now === 'unread') &&
      was !== undefined &&
      now !== undefined &&
      was !== 'deleted' &&
      now !== 'deleted';
    return !unknown && was !== now;
  });

/** `path` (absolute, or relative to `folder`, a folder of `repository`) relative to the repository's top, `/`-separated
 *  (`''`: the top itself); `undefined` outside it. The top git gives may be another spelling of `folder`'s (symbolic links resolved): a path in
 *  `folder` goes through `prefix`. */
export const within = ({ top, prefix }: Repository, folder: string, path: string) => {
  const inside = (base: string, file: string) => {
    const rel = relative(base, file);
    return rel.startsWith('..') || isAbsolute(rel) ? undefined : rel.split(sep).join('/');
  };
  const file = isAbsolute(path) ? path : join(folder, path);
  const local = inside(folder, file);
  return local === undefined ? inside(top, file) : `${prefix}${local}`.replace(/\/$/, '');
};

/** Git's own patch whatever the person's config: no external tool or textconv, the `a/` and `b/` prefixes the Changes
 *  panel reads (not `diff.mnemonicPrefix`'s `w/`, `i/`…), paths not quoted for their non-ASCII. */
const PATCH = ['--no-color', '--no-ext-diff', '--no-textconv', '--src-prefix=a/', '--dst-prefix=b/'];
const QUOTE = ['-c', 'core.quotePath=false'];

/** The diff of `files` against `HEAD` in `top` (an untracked file shown whole, as new), cut past `max` characters. An
 *  untracked file `sizeOf` (bytes, from its path relative to `top`) puts past `max`, or whose size it does not know, is
 *  one placeholder line: git is never asked for its patch (plugins#145). ponytail: the tracked part has no such cap. */
export const diffOf = async (
  run: Run,
  top: string,
  files: string[],
  max: number,
  sizeOf: (path: string) => Promise<number | undefined>,
) => {
  if (!files.length) return '';
  // `diff-index`, not `diff`: `diff` refreshes the index of a file whose stat moved (a `touch`), rewriting it through
  // `index.lock` even under `GIT_OPTIONAL_LOCKS=0`, and the session's agent's own `git add` then fails on that lock.
  const tracked = await run(top, [...QUOTE, 'diff-index', '-p', ...PATCH, 'HEAD', '--', ...files]);
  let text = tracked.stdout;
  const listed = await run(top, [
    'ls-files',
    '--others',
    '--exclude-standard',
    '-z',
    '--',
    ...files,
  ]);
  for (const path of listed.stdout.split('\0').filter(Boolean)) {
    if (text.length > max) break;
    const size = await sizeOf(path);
    if (size === undefined || size > max) {
      const what = size === undefined ? 'of unknown size' : `of ${size} bytes`;
      text += `diff --git a/${path} b/${path}\nnew file ${what}, not shown … [truncated]\n`;
      continue;
    }
    const added = await run(top, [...QUOTE, 'diff', ...PATCH, '--no-index', '--', '/dev/null', path]);
    text += added.stdout;
  }
  return text.length > max ? `${cutText(text, max)}\n… [truncated]` : text;
};

/** Commits exactly `files` in `top` (their current content, deletions included; nothing else staged goes in), with
 *  `message` and the trailer `Bridge-Session: <session>`; resolves to the new commit's sha, the files committed and the
 *  nested repositories `left` out. */
export const commit = async (
  run: Run,
  top: string,
  files: string[],
  message: string,
  session: string,
) => {
  // `commit --only` takes a tracked path's content from the disk, a deletion included (even one staged, as the old
  // side of a `git mv`, which `add` would refuse as matching no file); only an untracked one needs adding first.
  const listed = (
    await run(top, ['ls-files', '--others', '--exclude-standard', '-z', '--', ...files])
  ).stdout
    .split('\0')
    .filter(Boolean);
  // git lists a nested repository (and only one) as a folder, `sub/`: `add` would fail on an empty one and make a
  // gitlink of another; it stays out of the commit (plugins#145).
  const nested = new Set(listed.filter((path) => path.endsWith('/')));
  const untracked = listed.filter((path) => !nested.has(path));
  const left = files.filter((file) => nested.has(file) || nested.has(`${file}/`));
  const kept = files.filter((file) => !left.includes(file));
  // `commit --only` with no path would commit everything staged.
  if (!kept.length) throw new Error(`nothing to commit: ${left.join(', ')} are nested repositories`);
  if (untracked.length) {
    const added = await run(top, ['add', '--', ...untracked]);
    if (added.code !== 0) throw new Error(`git add failed: ${added.stderr.trim()}`);
  }
  const done = await run(top, [
    'commit',
    '--only',
    '-m',
    message,
    '--trailer',
    `Bridge-Session: ${session}`,
    '--',
    ...kept,
  ]);
  if (done.code !== 0) throw new Error(`git commit failed: ${(done.stderr || done.stdout).trim()}`);
  return { sha: (await run(top, ['rev-parse', 'HEAD'])).stdout.trim(), files: kept, left };
};
