"""Migration: agregar property_type + backfill de deals existentes.

Pasos:
1. init_db() — aplica ALTER TABLE idempotente (agrega columna property_type)
2. Para cada deal en deals.db:
   - Si property_type ya esta seteado y valido → skip
   - Else → infer_property_type() usando description/address/beds/source
3. UPDATE en bulk + reporte de distribucion

Usage:
    python scripts/migrate_property_type.py
"""
from __future__ import annotations
import io, sys
from pathlib import Path
from collections import Counter

sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8", errors="replace")
ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT))

from deals_db import init_db, _get_conn
from property_type_inference import infer_property_type, VALID_TYPES


def main() -> int:
    init_db()  # idempotent: aplica ALTER TABLE si la columna no existe
    conn = _get_conn()

    # Verificar que la columna existe ahora
    cols = {r["name"] for r in conn.execute("PRAGMA table_info(deals)").fetchall()}
    if "property_type" not in cols:
        print("ERROR: property_type column missing after init_db()")
        return 1
    print("Step 1: property_type column OK")

    rows = conn.execute(
        "SELECT id, source, address, listing_description, beds, baths, sqft, "
        "deal_type, property_type FROM deals"
    ).fetchall()
    print(f"Step 2: {len(rows)} deals to evaluate")
    print()

    counter_before = Counter()
    counter_after = Counter()
    updates = 0
    by_source: dict[str, Counter] = {}

    for r in rows:
        d = dict(r)
        before = d.get("property_type") or "(null)"
        counter_before[before] += 1

        new_pt = infer_property_type(d)
        counter_after[new_pt] += 1
        by_source.setdefault(d["source"], Counter())[new_pt] += 1

        if before != new_pt:
            conn.execute(
                "UPDATE deals SET property_type = ? WHERE id = ?",
                (new_pt, r["id"]),
            )
            updates += 1

    print(f"Updated: {updates}/{len(rows)} deals")
    print()
    print("=== Distribution BEFORE ===")
    for pt, n in sorted(counter_before.items(), key=lambda x: -x[1]):
        print(f"  {pt:<15} {n:>4}")
    print()
    print("=== Distribution AFTER ===")
    for pt, n in sorted(counter_after.items(), key=lambda x: -x[1]):
        print(f"  {pt:<15} {n:>4}")
    print()
    print("=== Breakdown por source ===")
    for source, c in by_source.items():
        print(f"  {source}:")
        for pt, n in sorted(c.items(), key=lambda x: -x[1]):
            print(f"    {pt:<15} {n:>4}")

    # Sanity: verificar que todos los property_type sean validos
    invalid = [pt for pt in counter_after if pt not in VALID_TYPES]
    if invalid:
        print(f"\nWARNING: invalid property_types produced: {invalid}")
        return 2

    print("\nDone.")
    return 0


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