"""`app.cli precedents list | show | overturn | export`: the register a pass reads and cannot edit
(Stream K12.3). Generated from decisions and notes; the export writes `docs/PRECEDENTS.md`."""

from __future__ import annotations

import argparse
import json
import pathlib
import sys

from app.db import SessionLocal
from app.services import precedents
from app.services.decisions.writer import Refused


def cmd_list(args: argparse.Namespace) -> int:
    with SessionLocal() as db:
        rows = precedents.describe(db)
        if args.json:
            print(json.dumps(rows, indent=1))
            return 0
        if not rows:
            print("no precedent set yet: every kind of question is new, and critical")
        for r in rows:
            flag = "" if r["status"] == "active" else "  OVERTURNED"
            print(f"{r['slug']:40s} {r['decisions_count']:4d} decisions  streak {r['streak']:2d}  resets {r['resets_count']}{flag}")
    return 0


def cmd_show(args: argparse.Namespace) -> int:
    with SessionLocal() as db:
        rows = [r for r in precedents.describe(db) if r["slug"] == args.slug]
        if not rows:
            print(f"no precedent {args.slug!r}", file=sys.stderr)
            return 1
        r = rows[0]
        print(json.dumps(r, indent=1))
        under = precedents.decisions_under(db, args.slug)
        print(f"{len(under)} decision(s) made under it")
    return 0


def cmd_overturn(args: argparse.Namespace) -> int:
    with SessionLocal() as db:
        try:
            out = precedents.overturn(db, args.slug, note=args.note, by=args.by, force=args.force)
        except Refused as exc:
            print(f"overturn refused: {exc.code}: {exc.summary}", file=sys.stderr)
            return 2
        print(f"{args.slug} overturned (decision {out['decision_uid']}, batch {out['batch_uid']}); "
              f"{out['decisions_under']} decision(s) were made under it and stay in force until a pass proposes against them")
    return 0


def cmd_export(args: argparse.Namespace) -> int:
    with SessionLocal() as db:
        text = precedents.export_markdown(db)
    if args.out == "-":
        print(text, end="")
    else:
        path = pathlib.Path(args.out)
        path.write_text(text, encoding="utf-8")
        print(f"wrote {path}")
    return 0


def register(sub) -> None:
    p = sub.add_parser("precedents", help="the register of kinds of judgement a person has answered (K12)")
    ps = p.add_subparsers(dest="precedents_command", required=True)
    ls = ps.add_parser("list", help="every precedent with its counts")
    ls.add_argument("--json", action="store_true")
    ls.set_defaults(func=cmd_list)
    sh = ps.add_parser("show", help="one precedent and the decisions made under it")
    sh.add_argument("slug")
    sh.set_defaults(func=cmd_show)
    ov = ps.add_parser("overturn", help="overturn a precedent: one undoable decision; regroups nothing")
    ov.add_argument("slug")
    ov.add_argument("--note", required=True, help="the new answer, in one sentence")
    ov.add_argument("--by", required=True, help="the account username")
    ov.add_argument("--force", action="store_true")
    ov.set_defaults(func=cmd_overturn)
    ex = ps.add_parser("export", help="write docs/PRECEDENTS.md (generated; never edited by hand)")
    ex.add_argument("--out", default="docs/PRECEDENTS.md", help="a path, or - for stdout")
    ex.set_defaults(func=cmd_export)
