import fs from 'node:fs';
import path from 'node:path';

/**
 * The canonical `.myco/.gitignore` body for the global-install model.
 *
 * Owned by the vault layer so the CLI (`update`), the daemon
 * auto-provisioner (`vault/provision.ts`), and the activation pipeline
 * can all write/refresh it without going through `cli/shared.ts`
 * (which has heavy transitive imports inappropriate for the activation
 * hot path).
 *
 * Plan reference: 38cff0752c919ffd §7. Post-migration, the project
 * vault carries only the deliberate project-level decisions
 * (myco.yaml, project.toml, .gitignore, tasks/) plus a small set of
 * per-machine artifacts gitignored here. The DB, embeddings, attachments,
 * secrets, daemon.json, team/, and installer-audit/ are Grove-scoped or
 * machine-global. buffer/, logs/, and machine_id are machine-global too,
 * but stay listed because a project vault can still carry stale or
 * transient copies.
 */
export const VAULT_GITIGNORE = `# Per-user, per-machine config overrides
local.yaml

# Project-scope runtime pin written by \`make dev-link\`. Per-machine,
# never committed.
runtime.command

# Per-machine ephemera; canonical copies live in ~/.myco/
buffer/
logs/
machine_id

# Per-project migration state — global-install sentinel and any future
# migration markers. Sentinel is per-machine because migration is a
# per-machine operation; teammates cloning the repo run their own.
migration/

# Staged files generated by the myco agent task that produces project
# skills. Exists only when the agent is mid-flight.
staging/

# Per-machine Grove binding. \`project.toml\` itself is committed
# (portable project + Grove identity); the binding lives here.
project.local.toml

# Migration archives — timestamped snapshots from the one-shot
# global-install migration and prior Grove activations. Forensics only;
# no rollback path. Local to this checkout.
.archive-*/
`;

/**
 * Write `<vaultDir>/.gitignore` to the canonical body if it's missing or
 * stale. Called from `myco update`, the Grove activation pipeline, and
 * project-manifest writes so users never have to wait for the next
 * update tick to keep machine-local files out of git. Idempotent —
 * exits without writing when the file already matches.
 */
export function ensureVaultGitignoreCurrent(vaultDir: string): boolean {
  const gitignorePath = path.join(vaultDir, '.gitignore');
  const current = fs.existsSync(gitignorePath) ? fs.readFileSync(gitignorePath, 'utf-8') : '';
  if (current === VAULT_GITIGNORE) return false;
  fs.mkdirSync(vaultDir, { recursive: true });
  fs.writeFileSync(gitignorePath, VAULT_GITIGNORE, 'utf-8');
  return true;
}
