"""Command-line entry point for the package."""
from __future__ import annotations

import argparse
import json
import sys
from pathlib import Path

from .collect import collect
from .report import (
    SubstituteRefusedError,
    populate_token_cells,
)


def main() -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument(
        "team_state",
        type=Path,
        help="Path to team-state JSON file",
    )
    parser.add_argument(
        "--project-root",
        type=Path,
        default=None,
        help="Override project root (default: inferred from team-state path)",
    )
    parser.add_argument(
        "--write",
        action="store_true",
        help=(
            "Write the updated team-state back to the same path "
            "(default: print to stdout)"
        ),
    )
    parser.add_argument(
        "--summary",
        action="store_true",
        help="Also print a one-line summary to stderr",
    )
    parser.add_argument(
        "--no-cache",
        action="store_true",
        help=(
            "Disable the incremental session-scan cache and force a full "
            "linear rescan of every session jsonl (correctness fallback)"
        ),
    )
    parser.add_argument(
        "--substitute-data",
        type=Path,
        default=None,
        help=(
            "After collecting usage, populate the final-report data.json "
            "at this path with concrete token / cost / duration values "
            "from the freshly computed usageSummary, then re-render the "
            "sibling final-report markdown via the renderer. The data.json "
            "is the SSOT; the markdown is regenerated from it. "
            "See schemas/final-report-v2.0.schema.json for the data shape."
        ),
    )
    parser.add_argument(
        "--record-observed-session",
        action="store_true",
        help=(
            "Observe the current live lead session and append it to the "
            "team-state's leadSessionIds/observedTeamNames (idempotent), "
            "print the appended sid, then exit"
        ),
    )
    args = parser.parse_args()

    if not args.team_state.is_file():
        print(f"team-state not found: {args.team_state}", file=sys.stderr)
        return 2

    if args.record_observed_session:
        from okstra_ctl.session import record_observed_lead_session

        from .collect import _infer_project_root

        if args.project_root is not None:
            project_root = args.project_root
        else:
            state = json.loads(args.team_state.read_text())
            project_root = _infer_project_root(args.team_state, state)
        sid = record_observed_lead_session(project_root, args.team_state)
        print(sid)
        return 0

    updated = collect(args.team_state, args.project_root,
                      incremental=not args.no_cache)

    if args.write:
        args.team_state.write_text(
            json.dumps(updated, indent=2, ensure_ascii=False) + "\n",
        )
    else:
        json.dump(updated, sys.stdout, indent=2, ensure_ascii=False)
        sys.stdout.write("\n")

    if args.summary:
        s = updated.get("usageSummary") or {}
        cost = s.get("estimatedCostUsd") or {}
        print(
            f"raw: lead={s.get('leadTotalTokens', 0):,} "
            f"workers={s.get('workerTotalTokens', 0):,} "
            f"grand={s.get('grandTotalTokens', 0):,}",
            file=sys.stderr,
        )
        print(
            f"billable-equiv: lead={s.get('leadBillableEquivalentTokens', 0):,} "
            f"workers={s.get('workerBillableEquivalentTokens', 0):,} "
            f"grand={s.get('grandBillableEquivalentTokens', 0):,}",
            file=sys.stderr,
        )
        print(
            f"cost USD: lead=${cost.get('lead', 0):.2f} "
            f"claude-workers=${cost.get('claudeWorkers', 0):.2f} "
            f"cli-workers=${cost.get('cliWorkers', 0):.2f} "
            f"grand=${cost.get('grandTotal', 0):.2f}",
            file=sys.stderr,
        )
        print(
            f"sessions={s.get('sessionsFound', 0)} "
            f"team={s.get('teamName', '')}",
            file=sys.stderr,
        )

    if args.substitute_data is not None:
        try:
            cells_changed = populate_token_cells(
                args.substitute_data,
                updated,
            )
        except SubstituteRefusedError as exc:
            print(
                f"final-report substitution REFUSED: {exc}",
                file=sys.stderr,
            )
            return 2
        print(
            f"final-report substitution: populated {cells_changed} cell(s) in "
            f"{args.substitute_data}. The full reading copy is on-demand.",
            file=sys.stderr,
        )

    return 0


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