#!/usr/bin/env python3
"""Apply saved corrections from JSON file to DB (crash recovery)."""

import argparse
import json
import logging
import os
from pathlib import Path

from sqlalchemy import create_engine, text

logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s")
logger = logging.getLogger("apply-corrections")

DB_URL = os.getenv("DATABASE_URL", "postgresql://breakpilot:breakpilot123@postgres:5432/breakpilot_db")


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("file", help="Path to corrections JSON file")
    parser.add_argument("--dry-run", action="store_true")
    args = parser.parse_args()

    corrections = json.loads(Path(args.file).read_text())
    logger.info("Loaded %d corrections from %s", len(corrections), args.file)

    if args.dry_run:
        for c in corrections[:10]:
            logger.info("  %s: %s → %s", c["uuid"][:8], c["old_hint"], c["new_hint"])
        logger.info("DRY RUN — not applying")
        return

    engine = create_engine(DB_URL, connect_args={"options": "-c search_path=compliance,public"})
    applied = 0
    with engine.begin() as c:
        c.execute(text("SET search_path TO compliance, public"))
        for corr in corrections:
            c.execute(text("""
                UPDATE canonical_controls
                SET generation_metadata = jsonb_set(
                    generation_metadata,
                    '{merge_group_hint}',
                    to_jsonb(CAST(:new_hint AS text))
                )
                WHERE id = CAST(:uuid AS uuid)
            """), {"uuid": corr["uuid"], "new_hint": corr["new_hint"]})
            applied += 1
    logger.info("Applied %d corrections.", applied)


if __name__ == "__main__":
    main()
