#!/usr/bin/env python3
"""Run the legacy -> R1 migration transforms (05-migration-plan step 2).

    python -m scripts.migrate_legacy [--dsn DSN] [--json PATH]

Without --dsn the sidecar URL comes from the environment/.env
(WITH_DB_URL in-container, WITH_DB_URL_HOST host-side). Exit codes:
0 = every legacy row accounted for; 1 = unexplained deltas or a hard
transform failure (the transaction was rolled back). Judgment #22
stragglers are WARNINGS (reported, attached, never an abort).
"""

import argparse
import json
import sys


def main(argv: list[str] | None = None) -> int:
    parser = argparse.ArgumentParser(description="Run the legacy->R1 transforms.")
    parser.add_argument("--dsn", help="target Postgres DSN (else WITH_DB_URL[_HOST])")
    parser.add_argument("--json", help="also write the full report JSON here")
    args = parser.parse_args(argv)

    from app.services.migrate import run_all

    # books_source="auto" enables the PlusROI sheet-books step (R2, ADR
    # #016): it auto-detects the app-relative books-import/source and runs
    # the sheet import inside the same rebuild transaction (missing export
    # → LOUD warn + skip, never a crash).
    report = run_all(args.dsn, books_source="auto")
    print(report.render())
    if args.json:
        with open(args.json, "w", encoding="utf-8") as fh:
            json.dump(report.as_dict(), fh, indent=2, default=str)
    return 0 if report.ok else 1


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