"""Jarvis Forge - a self-hosted, content-addressed code store.

Four objects, nothing more:

    blob    file bytes, named by sha256(bytes)
    tree    {path: {blob, size}}, named by sha256(canonical json)
    commit  {tree, parent, message, author, ts}, immutable, named by its own hash
    ref     a name pointing at a commit hash (main, wip, ...)

One linear history per ref. No branches, no rebase, no pull requests, no
remote protocol. What it adds instead is the thing a hosted forge cannot:
every commit writes a `code.commit` row to the MCA ledger, so code history
is as auditable as bot runs and covered by the same audit.verify().

This module imports nothing from Flask and nothing at module scope from the
orchestrator package, so it can be inspected, tested, or run standalone.

CLI
    python3 -m orchestrator.forge init
    python3 -m orchestrator.forge commit -m "message"
    python3 -m orchestrator.forge status
    python3 -m orchestrator.forge log
    python3 -m orchestrator.forge show <hash>
    python3 -m orchestrator.forge tree <hash>
    python3 -m orchestrator.forge cat <hash> <path>
    python3 -m orchestrator.forge diff <from> <to> [path]
    python3 -m orchestrator.forge index --out sites/forge-index
    python3 -m orchestrator.forge index --out sites/forge-index --publish
    python3 -m orchestrator.forge selftest

    --root DIR           work on that worktree instead of the current directory
    JARVIS_FORGE_ROOT    same thing, as an environment variable
    JARVIS_DB            where the forge database lives (default: <root>/jarvis.db)

Version history
    1.0.0  first build
    1.0.1  schema no longer writes on every connect (two-connection deadlock);
           .forgeignore supports directory entries with or without a slash;
           init/commit warn when the database sits inside the worktree;
           the selftest's secret check tested an impossible state
    1.0.2  an explicit root: --root, JARVIS_FORGE_ROOT, db_path follows it
    1.0.3  cwd is the actual default root - 1.0.2 still guessed based on
           marker files, so a plain `cd project && forge commit` quietly
           committed the installed package instead
"""

from __future__ import annotations

import fnmatch
import hashlib
import html as _html
import json
import os
import sqlite3
import subprocess
import sys
import zlib
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Iterable

FORGE_VERSION = "1.0.3"
SCHEMA_VERSION = 1
DEFAULT_REF = "main"
DEFAULT_AUTHOR = "ryan"

#: the package's parent - an explicit fallback, never a guess
REPO_ROOT = Path(__file__).resolve().parents[1]


def repo_root(explicit=None) -> Path:
    """The worktree to read or commit.

    Order: explicit argument, then JARVIS_FORGE_ROOT, then the current
    directory. cwd is the right default because it is what git does and what
    anyone expects from a CLI. Guessing based on marker files (looking for
    `orchestrator/` or `app.py`) means a plain `cd project && forge commit`
    silently operates on the installed package instead of the project.
    """
    if explicit:
        return Path(explicit).expanduser().resolve()
    env = os.environ.get("JARVIS_FORGE_ROOT")
    if env:
        return Path(env).expanduser().resolve()
    return Path.cwd().resolve()


#: directories never walked
IGNORE_DIRS = {
    ".venv", "venv", "env", ".git", "__pycache__", "node_modules", "backups",
    "sites", ".pytest_cache", "dist", "build", ".mypy_cache", ".ruff_cache",
    ".idea", ".vscode",
}

#: file patterns never walked - secrets and binaries live here
IGNORE_GLOBS = (
    "*.pyc", "*.pyo", "*.enc", "*.key", "*.pem", "*.p12",
    "token.txt", ".env", ".env.*", "*.bak", ".DS_Store",
    "jarvis.db", "jarvis.db-wal", "jarvis.db-shm",
    "*.log", "*.zip", "*.mp4", "*.mov",
)

#: names that must never leave the machine, even in a published index
SECRET_GLOBS = ("*.key", "*.pem", "*.enc", "token.txt", ".env", ".env.*", "jarvis.db*")

#: where the published index goes by default
DEFAULT_INDEX_OUT = "sites/forge-index"
INDEX_PROJECT = "jarvis-forge-index"


class ForgeError(RuntimeError):
    """A forge operation refused or failed. Always names why."""


# ---------------------------------------------------------------------------
# primitives
# ---------------------------------------------------------------------------
def now() -> str:
    return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")


def canon(obj: Any) -> bytes:
    """Canonical JSON: sorted keys, no whitespace, UTF-8. Stable bytes."""
    return json.dumps(obj, sort_keys=True, separators=(",", ":"),
                      ensure_ascii=False).encode("utf-8")


def digest(data: bytes) -> str:
    return hashlib.sha256(data).hexdigest()


def db_path() -> Path:
    env = os.environ.get("JARVIS_DB")
    if env:
        return Path(env).expanduser()
    return repo_root() / "jarvis.db"


def db_inside_worktree(root: Path | None = None) -> bool:
    """True when the forge database would land inside the tree it commits."""
    try:
        target = repo_root(root)
        db = db_path().resolve()
        return db.parent == target or target in db.parents
    except OSError:
        return False


def connect() -> sqlite3.Connection:
    p = db_path()
    p.parent.mkdir(parents=True, exist_ok=True)
    conn = sqlite3.connect(str(p), timeout=30)
    conn.row_factory = sqlite3.Row
    ensure_schema(conn)
    return conn


SCHEMA = """
CREATE TABLE IF NOT EXISTS forge_blobs (
    hash       TEXT PRIMARY KEY,
    size       INTEGER NOT NULL,
    data       BLOB NOT NULL,
    created_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS forge_trees (
    hash       TEXT PRIMARY KEY,
    entries    TEXT NOT NULL,
    created_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS forge_commits (
    hash       TEXT PRIMARY KEY,
    tree_hash  TEXT NOT NULL,
    parent     TEXT,
    message    TEXT NOT NULL,
    author     TEXT NOT NULL,
    ts         TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS forge_refs (
    name        TEXT PRIMARY KEY,
    commit_hash TEXT NOT NULL,
    updated_at  TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS forge_meta (
    k TEXT PRIMARY KEY,
    v TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_forge_commits_ts ON forge_commits(ts);
"""


def ensure_schema(conn: sqlite3.Connection) -> None:
    """Create the schema once. No write on an already-initialised database.

    The read-first check matters: writing on every connect() made a second
    connection fail immediately with "database is locked" whenever the first
    one held an open transaction.
    """
    row = conn.execute(
        "SELECT name FROM sqlite_master WHERE type='table' AND name='forge_meta'"
    ).fetchone()
    if row:
        return
    conn.executescript(SCHEMA)
    conn.execute(
        "INSERT OR REPLACE INTO forge_meta (k, v) VALUES ('schema_version', ?)",
        (str(SCHEMA_VERSION),),
    )
    conn.commit()


# ---------------------------------------------------------------------------
# blobs / trees / commits / refs
# ---------------------------------------------------------------------------
def put_blob(conn: sqlite3.Connection, h: str, data: bytes) -> int:
    """Store bytes under their hash. Returns 1 if new, 0 if already present."""
    cur = conn.execute("SELECT 1 FROM forge_blobs WHERE hash = ?", (h,))
    if cur.fetchone():
        return 0
    conn.execute(
        "INSERT INTO forge_blobs (hash, size, data, created_at) VALUES (?,?,?,?)",
        (h, len(data), zlib.compress(data, 9), now()),
    )
    return 1


def get_blob(conn: sqlite3.Connection, h: str) -> bytes:
    row = conn.execute("SELECT data FROM forge_blobs WHERE hash = ?", (h,)).fetchone()
    if not row:
        raise ForgeError("no blob %s" % h)
    return zlib.decompress(row["data"])


def put_tree(conn: sqlite3.Connection, h: str, entries: dict) -> None:
    conn.execute(
        "INSERT OR REPLACE INTO forge_trees (hash, entries, created_at) VALUES (?,?,?)",
        (h, canon(entries).decode("utf-8"), now()),
    )


def get_tree(conn: sqlite3.Connection, h: str) -> dict:
    row = conn.execute("SELECT entries FROM forge_trees WHERE hash = ?", (h,)).fetchone()
    if not row:
        raise ForgeError("no tree %s" % h)
    return json.loads(row["entries"])


def put_commit(conn: sqlite3.Connection, h: str, obj: dict) -> None:
    conn.execute(
        "INSERT OR REPLACE INTO forge_commits "
        "(hash, tree_hash, parent, message, author, ts) VALUES (?,?,?,?,?,?)",
        (h, obj["tree"], obj["parent"], obj["message"], obj["author"], obj["ts"]),
    )


def get_commit(conn: sqlite3.Connection, h: str) -> dict | None:
    row = conn.execute("SELECT * FROM forge_commits WHERE hash = ?", (h,)).fetchone()
    return dict(row) if row else None


def set_ref(conn: sqlite3.Connection, name: str, commit_hash: str) -> None:
    conn.execute(
        "INSERT OR REPLACE INTO forge_refs (name, commit_hash, updated_at) VALUES (?,?,?)",
        (name, commit_hash, now()),
    )


def get_ref(conn: sqlite3.Connection, name: str = DEFAULT_REF) -> str | None:
    row = conn.execute(
        "SELECT commit_hash FROM forge_refs WHERE name = ?", (name,)
    ).fetchone()
    return row["commit_hash"] if row else None


def list_refs(conn: sqlite3.Connection) -> list[dict]:
    rows = conn.execute(
        "SELECT name, commit_hash, updated_at FROM forge_refs ORDER BY name"
    ).fetchall()
    return [dict(r) for r in rows]


def log(conn: sqlite3.Connection, limit: int = 20, ref: str = DEFAULT_REF) -> list[dict]:
    """Walk parents from ref, newest first."""
    out = []
    h = get_ref(conn, ref)
    while h and len(out) < limit:
        c = get_commit(conn, h)
        if not c:
            break
        out.append(c)
        h = c["parent"]
    return out


def resolve(conn: sqlite3.Connection, ref_or_hash: str | None) -> str:
    """Accept a ref name, a full hash, or a unique prefix."""
    if not ref_or_hash:
        h = get_ref(conn)
        if not h:
            raise ForgeError("no commits yet - run: python3 -m orchestrator.forge commit -m 'first'")
        return h
    target = ref_or_hash.strip()
    h = get_ref(conn, target)
    if h:
        return h
    row = conn.execute(
        "SELECT hash FROM forge_commits WHERE hash = ?", (target,)
    ).fetchone()
    if row:
        return row["hash"]
    rows = conn.execute(
        "SELECT hash FROM forge_commits WHERE hash LIKE ? LIMIT 2", (target + "%",)
    ).fetchall()
    if len(rows) == 1:
        return rows[0]["hash"]
    if len(rows) > 1:
        raise ForgeError("ambiguous hash prefix: %s" % target)
    raise ForgeError("unknown ref or commit: %s" % target)


# ---------------------------------------------------------------------------
# worktree walking
# ---------------------------------------------------------------------------
def load_forgeignore(root: Path | None = None) -> tuple[str, ...]:
    f = repo_root(root) / ".forgeignore"
    if not f.exists():
        return ()
    out = []
    for line in f.read_text(encoding="utf-8").splitlines():
        line = line.strip()
        if line and not line.startswith("#"):
            out.append(line)
    return tuple(out)


def should_ignore(name: str, rel: str, extra: Iterable[str]) -> bool:
    """Pattern match against a filename, a relative path, or a directory component.

    Directory patterns work with or without a trailing slash, and a bare name
    matches any directory segment - so `.jarvis`, `.jarvis/` and `.jarvis/*`
    all behave the way they look.
    """
    parts = rel.split("/")
    parents = parts[:-1]
    for pat in tuple(IGNORE_GLOBS) + tuple(extra):
        p = pat.rstrip("/")
        if not p:
            continue
        if fnmatch.fnmatch(name, p) or fnmatch.fnmatch(rel, p):
            return True
        if pat.endswith("/") and (rel == p or rel.startswith(p + "/")):
            return True
        if "/" not in p and p in parents:
            return True
        if "*" in p and any(fnmatch.fnmatch(seg, p) for seg in parents):
            return True
    return False


def walk_worktree(root: Path | None = None,
                  extra_ignore: Iterable[str] = ()) -> list[tuple[str, bytes]]:
    """Every tracked file as (relative posix path, bytes). Sorted, deterministic."""
    root = repo_root(root)
    extra = tuple(load_forgeignore(root)) + tuple(extra_ignore)
    out: list[tuple[str, bytes]] = []
    for dirpath, dirnames, filenames in os.walk(root):
        dirnames[:] = sorted(
            d for d in dirnames if d not in IGNORE_DIRS and not d.startswith(".git")
        )
        base = Path(dirpath)
        rel_dir = base.relative_to(root)
        for name in sorted(filenames):
            rel = name if rel_dir == Path(".") else (rel_dir / name).as_posix()
            if should_ignore(name, rel, extra):
                continue
            p = base / name
            try:
                if p.is_symlink():
                    continue
                data = p.read_bytes()
            except OSError:
                continue
            out.append((rel, data))
    return out


def tree_from_files(files: list[tuple[str, bytes]]) -> dict:
    entries = {}
    for rel, data in files:
        entries[rel] = {"blob": digest(data), "size": len(data)}
    return entries


# ---------------------------------------------------------------------------
# ledger - the differentiator
# ---------------------------------------------------------------------------
def record_commit_ledger(commit_hash: str, commit_obj: dict, file_count: int) -> dict:
    """Write the code.commit row. Loud on failure - never silently skipped."""
    try:
        from . import audit  # late import: forge must work without the package
    except Exception as exc:
        return {"ok": False, "error": "audit unavailable: %s: %s"
                % (type(exc).__name__, exc)}
    try:
        row = audit.record(
            "forge",
            "code.commit",
            "commit",
            commit_hash,
            {
                "tree": commit_obj["tree"],
                "parent": commit_obj.get("parent"),
                "files": file_count,
                "message": (commit_obj.get("message") or "")[:200],
                "forge": FORGE_VERSION,
            },
        )
        return {"ok": True, "seq": (row or {}).get("seq")}
    except Exception as exc:
        return {"ok": False, "error": "%s: %s" % (type(exc).__name__, exc)}


# ---------------------------------------------------------------------------
# operations
# ---------------------------------------------------------------------------
def init(root: Path | None = None) -> dict:
    conn = connect()
    try:
        r = {"ok": True, "db": str(db_path()), "schema_version": SCHEMA_VERSION,
             "forge_version": FORGE_VERSION, "root": str(repo_root(root))}
        r["refs"] = list_refs(conn)
        if db_inside_worktree(root):
            r["warning"] = ("JARVIS_DB sits inside the worktree - the database "
                            "would commit itself. Point JARVIS_DB outside the repo.")
        return r
    finally:
        conn.close()


def status(root: Path | None = None, ref: str = DEFAULT_REF) -> dict:
    root = repo_root(root)
    files = walk_worktree(root)
    current = tree_from_files(files)
    current_hash = digest(canon(current))
    conn = connect()
    try:
        head = get_ref(conn, ref)
        if not head:
            return {"ok": True, "ref": ref, "commit": None, "clean": False,
                    "reason": "no commits yet", "files": len(current),
                    "tree": current_hash, "changes": {}}
        c = get_commit(conn, head)
        head_tree = get_tree(conn, c["tree_hash"])
        added = sorted(set(current) - set(head_tree))
        removed = sorted(set(head_tree) - set(current))
        modified = sorted(
            p for p in (set(current) & set(head_tree))
            if current[p]["blob"] != head_tree[p]["blob"]
        )
        clean = not (added or removed or modified)
        return {
            "ok": True, "ref": ref, "commit": head, "clean": clean,
            "files": len(current), "tree": current_hash,
            "changes": {"added": added, "modified": modified, "removed": removed},
        }
    finally:
        conn.close()


def commit(message: str, author: str = DEFAULT_AUTHOR, root: Path | None = None,
           ref: str = DEFAULT_REF, dry_run: bool = False,
           extra_ignore: Iterable[str] = ()) -> dict:
    root = repo_root(root)
    if not (message or "").strip():
        raise ForgeError("a commit needs a message: commit -m 'what changed'")
    files = walk_worktree(root, extra_ignore)
    if not files:
        raise ForgeError("nothing to commit: no files found under %s" % root)

    entries = tree_from_files(files)
    tree_hash = digest(canon(entries))

    conn = connect()
    try:
        parent = get_ref(conn, ref)
        if parent:
            pc = get_commit(conn, parent)
            if pc and pc["tree_hash"] == tree_hash:
                return {"committed": False, "reason": "no changes since %s" % parent,
                        "commit": parent, "tree": tree_hash, "files": len(files),
                        "new_blobs": 0, "parent": parent, "ledger": None}
        commit_obj = {
            "tree": tree_hash,
            "parent": parent,
            "message": message.strip(),
            "author": author,
            "ts": now(),
        }
        commit_hash = digest(canon(commit_obj))

        if dry_run:
            return {"committed": False, "dry_run": True, "commit": commit_hash,
                    "tree": tree_hash, "files": len(files), "new_blobs": "?",
                    "parent": parent, "ledger": None,
                    "would_store": sorted(entries)}

        new_blobs = sum(put_blob(conn, e["blob"], d) for (_, d), e in
                        zip(files, entries.values()))
        put_tree(conn, tree_hash, entries)
        put_commit(conn, commit_hash, commit_obj)
        set_ref(conn, ref, commit_hash)
        conn.commit()
    finally:
        conn.close()

    ledger = record_commit_ledger(commit_hash, commit_obj, len(files))
    return {"committed": True, "commit": commit_hash, "tree": tree_hash,
            "files": len(files), "new_blobs": new_blobs, "parent": parent,
            "ledger": ledger}


def diff(conn: sqlite3.Connection, a: str, b: str) -> dict:
    ca, cb = get_commit(conn, resolve(conn, a)), get_commit(conn, resolve(conn, b))
    if not ca or not cb:
        raise ForgeError("cannot diff: one side is missing")
    ta, tb = get_tree(conn, ca["tree_hash"]), get_tree(conn, cb["tree_hash"])
    return {
        "from": ca["hash"], "to": cb["hash"],
        "added": sorted(set(tb) - set(ta)),
        "removed": sorted(set(ta) - set(tb)),
        "modified": sorted(p for p in set(ta) & set(tb) if ta[p]["blob"] != tb[p]["blob"]),
    }


def line_diff(conn: sqlite3.Connection, a: str, b: str, path: str) -> str:
    ca, cb = get_commit(conn, resolve(conn, a)), get_commit(conn, resolve(conn, b))
    ta, tb = get_tree(conn, ca["tree_hash"]), get_tree(conn, cb["tree_hash"])
    old = get_blob(conn, ta[path]["blob"]).decode("utf-8", "replace") if path in ta else ""
    new = get_blob(conn, tb[path]["blob"]).decode("utf-8", "replace") if path in tb else ""
    import difflib
    return "".join(difflib.unified_diff(
        old.splitlines(keepends=True), new.splitlines(keepends=True),
        fromfile="a/" + path, tofile="b/" + path,
    ))


# ---------------------------------------------------------------------------
# the read-only index
# ---------------------------------------------------------------------------
def load_public_globs(root: Path | None = None) -> tuple[str, ...]:
    """Paths whose CONTENTS may be published. Empty = manifest only.

    This is the only control over what leaves the machine. It defaults to
    nothing, because a published index on a public host is public code.
    """
    f = repo_root(root) / "forge_public.txt"
    if not f.exists():
        return ()
    out = []
    for line in f.read_text(encoding="utf-8").splitlines():
        line = line.strip()
        if line and not line.startswith("#"):
            out.append(line)
    return tuple(out)


def _is_secret(path: str) -> bool:
    name = Path(path).name
    return any(fnmatch.fnmatch(name, g) or fnmatch.fnmatch(path, g) for g in SECRET_GLOBS)


def _content_allowed(path: str, globs: Iterable[str]) -> bool:
    return any(fnmatch.fnmatch(path, g) for g in globs)


def build_index(root: Path | None = None, ref: str = DEFAULT_REF,
                at: str | None = None, public_globs: Iterable[str] | None = None,
                max_commits: int = 50) -> dict:
    """Read-only snapshot of the forge: commits, tree, and opted-in contents."""
    root = repo_root(root)
    globs = tuple(public_globs) if public_globs is not None else load_public_globs(root)

    conn = connect()
    try:
        head = resolve(conn, at or ref)
        c = get_commit(conn, head)
        tree = get_tree(conn, c["tree_hash"])
        commits = log(conn, limit=max_commits, ref=ref) if at is None else [c]

        files = []
        contents: dict[str, str] = {}
        withheld: list[str] = []
        for path in sorted(tree):
            entry = tree[path]
            included = _content_allowed(path, globs)
            if included and _is_secret(path):
                withheld.append(path)
                included = False
            files.append({
                "path": path,
                "blob": entry["blob"],
                "size": entry["size"],
                "contents": included,
            })
            if included:
                raw = get_blob(conn, entry["blob"])
                try:
                    contents[path] = raw.decode("utf-8")
                except UnicodeDecodeError:
                    withheld.append(path + " (binary)")

        return {
            "forge": FORGE_VERSION,
            "generated_at": now(),
            "repo": Path(root).name,
            "ref": ref,
            "commit": head,
            "commit_message": c["message"],
            "commit_ts": c["ts"],
            "commits": [dict(x) for x in commits],
            "files": files,
            "contents": contents,
            "contents_included": sorted(contents),
            "contents_withheld": sorted(withheld),
            "public_globs": list(globs),
            "total_bytes": sum(f["size"] for f in files),
        }
    finally:
        conn.close()


INDEX_HTML = """<!doctype html>
<html lang="en"><head><meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Jarvis Forge - __REPO__</title>
<style>
:root{--bg:#070a10;--fg:#e6edf3;--dim:#8b98a8;--line:#1b2432;--acc:#2ad4ee;--vio:#a78bfa}
*{box-sizing:border-box}
body{margin:0;background:var(--bg);color:var(--fg);font:15px/1.55 ui-sans-serif,-apple-system,Segoe UI,Roboto,sans-serif}
.wrap{max-width:1000px;margin:0 auto;padding:36px 20px 80px}
h1{font-size:24px;margin:0 0 4px;letter-spacing:-.02em}
h1 span{color:var(--acc)}
.sub{color:var(--dim);font-size:13px;margin:0 0 24px;font-family:ui-monospace,SFMono-Regular,Menlo,monospace}
.grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(150px,1fr));gap:10px;margin:0 0 26px}
.card{background:#0c111a;border:1px solid var(--line);border-radius:10px;padding:12px 14px}
.card .k{color:var(--dim);font-size:11px;text-transform:uppercase;letter-spacing:.08em;font-family:ui-monospace,monospace}
.card .v{font-size:19px;margin-top:4px;font-family:ui-monospace,monospace}
h2{font-size:13px;text-transform:uppercase;letter-spacing:.1em;color:var(--dim);margin:30px 0 10px;font-weight:600}
table{width:100%;border-collapse:collapse;font-size:13.5px}
th{text-align:left;color:var(--dim);font-weight:600;font-size:11px;text-transform:uppercase;letter-spacing:.07em;padding:0 10px 7px 0;border-bottom:1px solid var(--line)}
td{padding:7px 10px 7px 0;border-bottom:1px solid #11161f;vertical-align:top}
td.mono,a.mono{font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:12.5px}
a{color:var(--acc);text-decoration:none}a:hover{text-decoration:underline}
.yes{color:#34d399}.no{color:#5b6675}
.note{background:#0c111a;border:1px solid var(--line);border-left:3px solid var(--vio);border-radius:8px;padding:12px 14px;color:var(--dim);font-size:13px;margin:0 0 24px}
.note b{color:var(--fg)}
.msgs{color:var(--fg)}
footer{color:#5b6675;font-size:12px;margin-top:34px;border-top:1px solid var(--line);padding-top:14px}
</style></head><body><div class="wrap">
<h1>Jarvis Forge <span>&#9679;</span> __REPO__</h1>
<p class="sub">content-addressed code store &middot; every commit is a ledger row</p>
<div class="note"><b>This is a read-only index.</b> It shows what the forge holds and, for paths explicitly listed in <span class="mono">forge_public.txt</span>, links to the file contents. Nothing else leaves the machine.</div>
<div class="grid">
<div class="card"><div class="k">ref</div><div class="v">__REF__</div></div>
<div class="card"><div class="k">head</div><div class="v">__SHORT__</div></div>
<div class="card"><div class="k">files</div><div class="v">__NFILES__</div></div>
<div class="card"><div class="k">commits</div><div class="v">__NCOMMITS__</div></div>
<div class="card"><div class="k">size</div><div class="v">__SIZE__</div></div>
</div>
<h2>History</h2>
<table><thead><tr><th>commit</th><th>when</th><th>message</th></tr></thead><tbody>
__COMMITS__
</tbody></table>
<h2>Tree</h2>
<table><thead><tr><th>path</th><th>blob</th><th>size</th><th>contents</th></tr></thead><tbody>
__FILES__
</tbody></table>
__WITHHELD__
<footer>generated __GENERATED__ &middot; forge __VERSION__ &middot; read-only, nothing here is writable</footer>
</div></body></html>
"""


def render_index_html(idx: dict) -> str:
    def esc(v: Any) -> str:
        return _html.escape(str(v), quote=True)

    def hsize(n: int) -> str:
        f = float(n)
        for unit in ("B", "KB", "MB"):
            if f < 1024 or unit == "MB":
                return ("%.0f %s" % (f, unit)) if unit == "B" else ("%.1f %s" % (f, unit))
            f /= 1024.0
        return "%d B" % n

    commits = "\n".join(
        "<tr><td class=mono><a href='#%s'>%s</a></td><td class=mono>%s</td>"
        "<td class=msgs>%s</td></tr>"
        % (esc(c["hash"]), esc(c["hash"][:10]), esc(c["ts"]), esc(c["message"]))
        for c in idx["commits"]
    ) or "<tr><td colspan=3 class='no'>no commits yet</td></tr>"

    rows = []
    for f in idx["files"]:
        if f["contents"]:
            target = "files/" + f["path"]
            cell = "<a class='mono' href='%s'>view</a>" % esc(target)
            label = "<a class='mono' href='%s'>%s</a>" % (esc(target), esc(f["path"]))
        else:
            cell = "<span class=no>withheld</span>"
            label = "<span class=mono>%s</span>" % esc(f["path"])
        rows.append(
            "<tr><td>%s</td><td class=mono>%s</td><td class=mono>%s</td><td>%s</td></tr>"
            % (label, esc(f["blob"][:10]), esc(hsize(f["size"])), cell)
        )
    files_html = "\n".join(rows) or "<tr><td colspan=4 class='no'>empty tree</td></tr>"

    withheld = ""
    if idx["contents_withheld"]:
        items = "".join("<li class=mono>%s</li>" % esc(p) for p in idx["contents_withheld"])
        withheld = ("<h2>Withheld</h2><div class='note'>These matched a public glob "
                    "but were refused because they look like secrets or binaries:"
                    "<ul>%s</ul></div>" % items)

    return (INDEX_HTML
            .replace("__REPO__", esc(idx["repo"]))
            .replace("__REF__", esc(idx["ref"]))
            .replace("__SHORT__", esc(idx["commit"][:10]))
            .replace("__NFILES__", str(len(idx["files"])))
            .replace("__NCOMMITS__", str(len(idx["commits"])))
            .replace("__SIZE__", hsize(idx["total_bytes"]))
            .replace("__COMMITS__", commits)
            .replace("__FILES__", files_html)
            .replace("__WITHHELD__", withheld)
            .replace("__GENERATED__", esc(idx["generated_at"]))
            .replace("__VERSION__", esc(idx["forge"])))


def write_index(out_dir: Path, idx: dict) -> dict:
    out_dir = Path(out_dir)
    out_dir.mkdir(parents=True, exist_ok=True)
    (out_dir / "files").mkdir(exist_ok=True)

    public = dict(idx)
    public.pop("contents", None)
    (out_dir / "index.json").write_text(
        json.dumps(public, indent=2, sort_keys=True), encoding="utf-8"
    )
    (out_dir / "index.html").write_text(render_index_html(idx), encoding="utf-8")

    written = ["index.json", "index.html"]
    for path, text in idx["contents"].items():
        dest = out_dir / "files" / path
        dest.parent.mkdir(parents=True, exist_ok=True)
        dest.write_text(text, encoding="utf-8")
        written.append("files/" + path)

    return {"out": str(out_dir), "written": written,
            "contents": len(idx["contents"]),
            "withheld": len(idx["contents_withheld"])}


def publish_index(out_dir: Path, project: str = INDEX_PROJECT) -> dict:
    """Deploy the index with wrangler. OAuth credentials, no API token needed."""
    out_dir = Path(out_dir).resolve()
    if not (out_dir / "index.html").exists():
        raise ForgeError("nothing to publish: %s has no index.html" % out_dir)
    cmd = ["npx", "--yes", "wrangler@latest", "pages", "deploy", str(out_dir),
           "--project-name", project, "--branch", "main", "--commit-dirty=true"]
    env = os.environ.copy()
    env.setdefault("CI", "1")
    proc = subprocess.run(cmd, capture_output=True, text=True, env=env)
    output = (proc.stdout or "") + (proc.stderr or "")
    url = None
    for token in output.replace("|", " ").replace(":", " ").split():
        if token.startswith("https://") and ".pages.dev" in token:
            url = token.rstrip(".,)")
    if proc.returncode != 0:
        return {"ok": False, "returncode": proc.returncode,
                "error": output.strip()[:900], "url": url}
    return {"ok": True, "url": url, "project": project,
            "stable_url": "https://%s.pages.dev" % project}


# ---------------------------------------------------------------------------
# self-test
# ---------------------------------------------------------------------------
def selftest() -> dict:
    import shutil
    import tempfile

    results: list[tuple[str, bool, str]] = []

    def check(name, cond, detail=""):
        results.append((name, bool(cond), detail))

    tmp = Path(tempfile.mkdtemp(prefix="forge-selftest-"))
    work = tmp / "repo"
    old_db = os.environ.get("JARVIS_DB")
    old_root = os.environ.pop("JARVIS_FORGE_ROOT", None)
    old_cwd = os.getcwd()
    try:
        os.environ["JARVIS_DB"] = str(tmp / "forge.db")
        (work / "pkg").mkdir(parents=True)
        (work / "README.md").write_text("# demo\n", encoding="utf-8")
        (work / "pkg" / "a.py").write_text("print('a')\n", encoding="utf-8")

        # --- primitives -------------------------------------------------
        check("canon is byte-stable", canon({"b": 1, "a": 2}) == canon({"a": 2, "b": 1}))
        check("digest matches sha256", digest(b"x") == hashlib.sha256(b"x").hexdigest())

        # --- root resolution --------------------------------------------
        os.chdir(str(work))
        check("repo_root follows cwd", repo_root() == work.resolve(),
              "%s != %s" % (repo_root(), work.resolve()))
        os.environ["JARVIS_FORGE_ROOT"] = str(tmp)
        check("repo_root honours JARVIS_FORGE_ROOT", repo_root() == Path(tmp).resolve())
        os.environ.pop("JARVIS_FORGE_ROOT", None)
        check("explicit root beats cwd", repo_root(tmp) == Path(tmp).resolve(),
              "%s != %s" % (repo_root(tmp), Path(tmp).resolve()))

        # --- commits ----------------------------------------------------
        r1 = commit("first commit", root=work)
        check("first commit lands", r1["committed"] and len(r1["commit"]) == 64,
              r1["commit"][:12])
        check("two files tracked", r1["files"] == 2, str(r1["files"]))
        check("parent is None", r1["parent"] is None)

        r2 = commit("first commit again", root=work)
        check("no-op commit refused", r2["committed"] is False, r2.get("reason", ""))

        (work / "pkg" / "a.py").write_text("print('a')\nprint('b')\n", encoding="utf-8")
        (work / "new.txt").write_text("new\n", encoding="utf-8")
        r3 = commit("second commit", root=work)
        check("second commit lands", r3["committed"], r3["commit"][:12])
        check("parent chains", r3["parent"] == r1["commit"])
        check("only changed blobs stored", r3["new_blobs"] == 2, str(r3["new_blobs"]))

        st = status(root=work)
        check("status clean after commit", st["clean"] is True)
        (work / "new.txt").write_text("changed\n", encoding="utf-8")
        st2 = status(root=work)
        check("status sees modification", st2["changes"]["modified"] == ["new.txt"],
              str(st2["changes"]["modified"]))
        commit("third commit", root=work)

        # --- read side --------------------------------------------------
        conn = connect()
        try:
            lg = log(conn, limit=5)
            check("log walks parents", len(lg) == 3, str(len(lg)))
            d = diff(conn, r1["commit"], r3["commit"])
            check("diff finds the new file", d["added"] == ["new.txt"], str(d["added"]))
            check("diff finds the edit", "pkg/a.py" in d["modified"], str(d["modified"]))
            text = line_diff(conn, r1["commit"], r3["commit"], "pkg/a.py")
            check("line diff has +b", "+print('b')" in text)
            head = resolve(conn, "main")
            check("resolve ref works", head == get_ref(conn, "main"))
            check("resolve prefix works", resolve(conn, head[:8]) == head)
            t = get_tree(conn, get_commit(conn, head)["tree_hash"])
            blob = get_blob(conn, t["README.md"]["blob"])
            check("blob round-trips through zlib", blob == b"# demo\n")
        finally:
            conn.close()

        # --- secrets never enter the tree -------------------------------
        (work / "token.txt").write_text("super-secret\n", encoding="utf-8")
        (work / ".env").write_text("KEY=1\n", encoding="utf-8")
        (work / "x.pem").write_text("-----BEGIN-----\n", encoding="utf-8")
        (work / "keep.py").write_text("keep\n", encoding="utf-8")
        tracked = dict(walk_worktree(work))
        check("token.txt never walked", "token.txt" not in tracked)
        check(".env never walked", ".env" not in tracked)
        check("*.pem never walked", "x.pem" not in tracked)
        check("normal file still tracked", "keep.py" in tracked)
        check("_is_secret names a token file", _is_secret("token.txt"))
        check("_is_secret clears a source file", not _is_secret("keep.py"))

        # --- .forgeignore ----------------------------------------------
        check("dir pattern with slash ignores children",
              should_ignore("forge.db", ".jarvis/forge.db", (".jarvis/",)))
        check("dir pattern without slash ignores children",
              should_ignore("forge.db", ".jarvis/forge.db", (".jarvis",)))
        check("glob dir pattern ignores children",
              should_ignore("forge.db", ".jarvis/forge.db", (".jarvis/*",)))
        check("unrelated path is not ignored",
              not should_ignore("a.py", "pkg/a.py", (".jarvis/",)))

        # --- index ------------------------------------------------------
        commit("fourth commit", root=work)
        idx = build_index(root=work, public_globs=())
        check("index has a head", len(idx["commit"]) == 64)
        check("index lists the tree", len(idx["files"]) >= 3, str(len(idx["files"])))
        check("index withholds all contents by default", idx["contents_included"] == [],
              str(idx["contents_included"]))
        check("nothing withheld when nothing was opted in",
              idx["contents_withheld"] == [], str(idx["contents_withheld"]))

        idx2 = build_index(root=work, public_globs=("pkg/a.py", "README.md"))
        check("opted-in contents appear",
              set(idx2["contents_included"]) == {"pkg/a.py", "README.md"},
              str(idx2["contents_included"]))
        check("unlisted paths stay withheld in the tree",
              all(not f["contents"] for f in idx2["files"] if f["path"] == "keep.py"))

        out = tmp / "index-out"
        w = write_index(out, idx2)
        check("index files written",
              (out / "index.html").exists() and (out / "index.json").exists())
        check("opted-in file written to disk", (out / "files" / "README.md").exists())
        check("unlisted file not written to disk",
              not (out / "files" / "keep.py").exists())
        check("written list matches", len(w["written"]) == 4, str(w["written"]))

        html_text = (out / "index.html").read_text(encoding="utf-8")
        json_text = (out / "index.json").read_text(encoding="utf-8")
        check("html is self-contained",
              "<link" not in html_text and "<script" not in html_text)
        check("html has no unresolved placeholder", "__" not in html_text)
        check("html links to the published file", "files/README.md" in html_text)
        check("index.json carries no file bodies", "print('b')" not in json_text)

        # --- content addressing detects a forged tree -------------------
        conn = connect()
        try:
            head = get_ref(conn, "main")
            real = get_tree(conn, get_commit(conn, head)["tree_hash"])
            check("tree hash recomputes",
                  digest(canon(real)) == get_commit(conn, head)["tree_hash"])
            forged = dict(real)
            forged["README.md"] = {"blob": "0" * 64, "size": 7}
            check("edited tree changes its hash",
                  digest(canon(forged)) != get_commit(conn, head)["tree_hash"])
        finally:
            conn.close()

        # --- two live connections must not deadlock ---------------------
        c1 = connect()
        try:
            c1.execute("INSERT OR REPLACE INTO forge_meta (k, v) VALUES ('t','1')")
            c2 = connect()
            try:
                check("second connection opens under an open write", True)
            finally:
                c2.close()
            c1.rollback()
        except sqlite3.OperationalError as exc:
            check("second connection opens under an open write", False, str(exc))
        finally:
            c1.close()

        # --- the database must not live inside the tree -----------------
        os.environ["JARVIS_DB"] = str(work / "inside.db")
        check("warns when the db is inside the worktree", db_inside_worktree(work) is True)
        os.environ["JARVIS_DB"] = str(tmp / "outside.db")
        check("quiet when the db is outside", db_inside_worktree(work) is False)

    except Exception as exc:
        import traceback
        results.append(("selftest crashed", False,
                        "%s: %s | %s" % (type(exc).__name__, exc,
                                         traceback.format_exc().splitlines()[-3:])))
    finally:
        os.chdir(old_cwd)
        if old_db is None:
            os.environ.pop("JARVIS_DB", None)
        else:
            os.environ["JARVIS_DB"] = old_db
        if old_root is not None:
            os.environ["JARVIS_FORGE_ROOT"] = old_root
        shutil.rmtree(tmp, ignore_errors=True)

    passed = sum(1 for _, ok, _ in results if ok)
    return {"passed": passed, "total": len(results),
            "failed": [(n, d) for n, ok, d in results if not ok],
            "ok": passed == len(results)}


# ---------------------------------------------------------------------------
# CLI
# ---------------------------------------------------------------------------
def _print(obj: Any) -> None:
    if isinstance(obj, (dict, list)):
        print(json.dumps(obj, indent=2, sort_keys=True, default=str))
    else:
        print(obj)


def main(argv: list[str] | None = None) -> int:
    argv = list(sys.argv[1:] if argv is None else argv)
    if not argv:
        print(__doc__)
        return 2

    cmd, rest = argv[0], argv[1:]

    # --root DIR overrides the worktree for this invocation.
    root_arg = None
    if "--root" in rest:
        i = rest.index("--root")
        if i + 1 < len(rest):
            root_arg = rest[i + 1]
        cleaned, skip = [], False
        for a in rest:
            if skip:
                skip = False
                continue
            if a == "--root":
                skip = True
                continue
            cleaned.append(a)
        rest = cleaned
    if root_arg:
        os.environ["JARVIS_FORGE_ROOT"] = root_arg

    def flag(names, default=None):
        for n in names:
            if n in rest:
                i = rest.index(n)
                return rest[i + 1] if i + 1 < len(rest) else default
        return default

    try:
        if cmd == "init":
            _print(init(root_arg))
            return 0

        if cmd in ("commit", "-m"):
            msg = flag(["-m", "--message"]) or " ".join(rest)
            if db_inside_worktree(root_arg):
                print("WARNING: JARVIS_DB is inside the worktree - the database "
                      "would commit itself.", file=sys.stderr)
            r = commit(msg, root=root_arg, dry_run="--dry-run" in rest)
            _print(r)
            if r.get("ledger") and not r["ledger"].get("ok"):
                print("WARNING: ledger row failed: %s" % r["ledger"]["error"],
                      file=sys.stderr)
                return 1
            return 0 if r.get("committed") or str(r.get("reason", "")).startswith("no changes") else 1

        if cmd == "status":
            _print(status(root=root_arg))
            return 0

        if cmd == "log":
            n = int(flag(["-n", "--limit"], "20"))
            conn = connect()
            try:
                rows = log(conn, limit=n)
            finally:
                conn.close()
            if not rows:
                print("no commits yet")
                return 0
            for c in rows:
                print("%s  %s  %s" % (c["hash"][:10], c["ts"], c["message"]))
            return 0

        if cmd == "show":
            conn = connect()
            try:
                h = resolve(conn, rest[0] if rest else None)
                c = get_commit(conn, h)
                t = get_tree(conn, c["tree_hash"])
            finally:
                conn.close()
            _print({"commit": c, "files": len(t), "tree": sorted(t)})
            return 0

        if cmd == "tree":
            conn = connect()
            try:
                h = resolve(conn, rest[0] if rest else None)
                t = get_tree(conn, get_commit(conn, h)["tree_hash"])
            finally:
                conn.close()
            for p in sorted(t):
                print("%s  %10d  %s" % (t[p]["blob"][:10], t[p]["size"], p))
            return 0

        if cmd in ("cat", "diff"):
            conn = connect()
            try:
                if cmd == "cat":
                    if len(rest) < 2:
                        raise ForgeError("usage: cat <commit> <path>")
                    h = resolve(conn, rest[0])
                    t = get_tree(conn, get_commit(conn, h)["tree_hash"])
                    path = rest[1]
                    if path not in t:
                        raise ForgeError("%s is not in %s" % (path, h[:10]))
                    sys.stdout.write(
                        get_blob(conn, t[path]["blob"]).decode("utf-8", "replace"))
                else:
                    if len(rest) >= 3:
                        sys.stdout.write(line_diff(conn, rest[0], rest[1], rest[2]))
                    elif len(rest) == 2:
                        d = diff(conn, rest[0], rest[1])
                        for p in d["added"]:
                            print("A  " + p)
                        for p in d["modified"]:
                            print("M  " + p)
                        for p in d["removed"]:
                            print("D  " + p)
                    else:
                        raise ForgeError("usage: diff <from> <to> [path]")
            finally:
                conn.close()
            return 0

        if cmd == "index":
            out = Path(flag(["--out", "-o"], DEFAULT_INDEX_OUT))
            globs = None
            if "--public" in rest:
                vals = []
                for i, a in enumerate(rest):
                    if a == "--public" and i + 1 < len(rest):
                        vals.append(rest[i + 1])
                globs = tuple(vals)
            idx = build_index(root=root_arg, public_globs=globs)
            w = write_index(out, idx)
            _print({"index": w, "commit": idx["commit"], "files": len(idx["files"]),
                    "contents_included": idx["contents_included"],
                    "contents_withheld": idx["contents_withheld"]})
            if "--publish" in rest:
                p = publish_index(out)
                _print({"publish": p})
                return 0 if p.get("ok") else 1
            return 0

        if cmd == "selftest":
            r = selftest()
            for name, detail in r["failed"]:
                print("FAIL  %s  %s" % (name, detail))
            print("SELFTEST %s (%d/%d checks)" %
                  ("PASS" if r["ok"] else "FAIL", r["passed"], r["total"]))
            return 0 if r["ok"] else 1

        print("unknown command: %s" % cmd, file=sys.stderr)
        print(__doc__, file=sys.stderr)
        return 2

    except ForgeError as exc:
        print("FORGE ERROR: %s" % exc, file=sys.stderr)
        return 1


if __name__ == "__main__":
    raise SystemExit(main())