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

/** 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,
      '',
    );

/** A model's answer as a `type/topic` branch name (`fix/e2e-shards`), `undefined` when it is not one. */
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
    : undefined;
};

/** `name`, else `name-2`, `name-3`…: the first that no branch of the repository at `folder` has. */
export const freeBranch = async (run: Run, folder: string, name: string) => {
  const { stdout } = await run(folder, ['branch', '--list', '--format=%(refname:short)']);
  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;
}

/** 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) => {
  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.map(async (path) => state.set(path, await fingerprint(owner, join(top, path)))),
  );
  return state;
};

/** Read through the host (`ctx.fs`) as `owner`. */
const fingerprint = async (owner: Context, file: string) => {
  try {
    const info = await owner.fs.stat(owner, file);
    if (!info) return 'deleted';
    if (!info.isFile) return `other:${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`. */
export const changed = (before: Map<string, string>, after: Map<string, string>) =>
  [...new Set([...before.keys(), ...after.keys()])].filter(
    (path) => before.get(path) !== after.get(path),
  );

/** `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 diff` printing 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 = [
  '-c',
  'core.quotePath=false',
  'diff',
  '--no-color',
  '--no-ext-diff',
  '--no-textconv',
  '--src-prefix=a/',
  '--dst-prefix=b/',
];

/** The diff of `files` against `HEAD` in `top` (an untracked file shown whole, as new), cut past `max` characters. */
export const diffOf = async (run: Run, top: string, files: string[], max: number) => {
  if (!files.length) return '';
  const tracked = await run(top, [...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 added = await run(top, [...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. */
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 untracked = (
    await run(top, ['ls-files', '--others', '--exclude-standard', '-z', '--', ...files])
  ).stdout
    .split('\0')
    .filter(Boolean);
  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}`,
    '--',
    ...files,
  ]);
  if (done.code !== 0) throw new Error(`git commit failed: ${(done.stderr || done.stdout).trim()}`);
  return (await run(top, ['rev-parse', 'HEAD'])).stdout.trim();
};
