"""runner docs pull — hydrate the agent's local context (prod.md §Context pack).

Fetches the versioned Markdown pack from the server and writes CLAUDE.md +
.runner/docs/*. Never clobbers a user's own notes: any path ending in `.local.md`
is left untouched, and we record the pack version in .runner/config.json so a
no-change pull is a cheap no-op.
"""
import sys
from pathlib import Path

from . import api, config


def pull(scope=None, target="claude"):
    params = {"target": target, "runtime": "pip"}  # picks the venv-specific wire-in block in CLAUDE.md
    sc = scope or config.default_scope()
    if sc:
        params["scope"] = sc
    try:
        pack = api.get("/api/v1/context-pack", params)
    except api.ApiError as e:
        print(f"docs pull failed: {e}", file=sys.stderr)
        return 1

    written, skipped = [], []
    for rel, content in pack["files"].items():
        p = Path(rel)
        if p.name.endswith(".local.md"):
            skipped.append(rel)
            continue
        p.parent.mkdir(parents=True, exist_ok=True)
        p.write_text(content)
        written.append(rel)

    config.set_project(context_version=pack.get("version"), workspace=pack.get("workspace"))
    print(f"docs: wrote {len(written)} files (version {pack.get('version')})", file=sys.stderr)
    for w in written:
        print(f"  {w}", file=sys.stderr)
    if skipped:
        print(f"  kept {len(skipped)} *.local.md untouched", file=sys.stderr)
    return 0
