"""Nova Decision Ledger CLI (REQ-207).

Subcommands: query, verify-chain, stats, export, replay.
Read-only CLI for the Decision Ledger SQLite hash-chain.
"""

import json
import os
import sys

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
from core.metrics.decision_ledger import query_by_run, verify_chain, stats, export_since, replay_run


def main():
    if len(sys.argv) < 2:
        print("usage: decision_ledger_cli.py <query|verify-chain|stats|export|replay> [args]", file=sys.stderr)
        sys.exit(2)
    cmd = sys.argv[1]
    if cmd == "query" and len(sys.argv) >= 3:
        print(json.dumps(query_by_run(sys.argv[2]), indent=2))
    elif cmd == "verify-chain":
        ok, broken, details = verify_chain()
        print(f"chain_ok={ok} broken={broken} details={details}")
        sys.exit(0 if ok else 1)
    elif cmd == "stats":
        print(json.dumps(stats(), indent=2))
    elif cmd == "export" and len(sys.argv) >= 3:
        fmt = sys.argv[3] if len(sys.argv) >= 4 else "json"
        print(export_since(sys.argv[2], fmt=fmt))
    elif cmd == "replay" and len(sys.argv) >= 3:
        print(replay_run(sys.argv[2]))
    else:
        print(f"unknown command: {cmd}", file=sys.stderr)
        sys.exit(2)


if __name__ == "__main__":
    main()