#!/usr/bin/env python3
"""Preview what the OKF hook would inject, without starting Claude Code.

    bin/okf-reader-preview [PROJECT] [--standards DIR] [--cache-dir DIR]
                            [--event SessionStart|SubagentStart] [--raw]

Exits 1 when the hook produced nothing, so it is usable in CI as a check that a
project's bundles still resolve.
"""

from __future__ import annotations

import argparse
import json
import os
import subprocess
import sys
from pathlib import Path

HOOK = Path(__file__).resolve().parent / "../scripts" / "okf_context.py"


def main() -> int:
    parser = argparse.ArgumentParser(description=__doc__,
                                     formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument("project", nargs="?", default=".", help="project root (default: cwd)")
    parser.add_argument("--standards", help="CLAUDE_PLUGIN_OPTION_STANDARDS_BUNDLE")
    parser.add_argument("--cache-dir", help="CLAUDE_PLUGIN_OPTION_CACHE_DIR")
    parser.add_argument("--event", default="SessionStart",
                        choices=["SessionStart", "SubagentStart"])
    parser.add_argument("--raw", action="store_true", help="print the JSON the hook emits")
    args = parser.parse_args()

    project = Path(args.project).expanduser().resolve()
    if not project.is_dir():
        print(f"no such directory: {project}", file=sys.stderr)
        return 2

    env = dict(os.environ)
    for flag, key in (
        (args.standards, "STANDARDS_BUNDLE"),
        (args.cache_dir, "CACHE_DIR"),
    ):
        if flag is not None:
            env[f"CLAUDE_PLUGIN_OPTION_{key}"] = str(flag)

    proc = subprocess.run(
        [sys.executable, str(HOOK)],
        input=json.dumps({"cwd": str(project), "hook_event_name": args.event}),
        capture_output=True, text=True, env=env,
    )

    if proc.stderr:
        print("\n".join(f"  warning: {line}" for line in proc.stderr.strip().splitlines()),
              file=sys.stderr)

    if not proc.stdout.strip():
        print(f"\nNo OKF bundle resolved in {project}.", file=sys.stderr)
        print("The hook would stay silent and cost nothing.", file=sys.stderr)
        return 1

    if args.raw:
        print(proc.stdout.rstrip())
        return 0

    context = json.loads(proc.stdout)["hookSpecificOutput"]["additionalContext"]
    chars = len(context)
    print(f"\n{'=' * 72}\n{args.event}: {chars} chars (~{chars // 4} tokens)\n{'=' * 72}\n")
    print(context)
    return 0


if __name__ == "__main__":
    sys.exit(main())