#!/usr/bin/env python3
"""
Third pass: clean specific remaining supplier-corrupted models.

Usage:
    python scripts/clean_supplier_corrupted_models_v3.py [--execute]
"""

import os
import sys

import psycopg2

MASTER_DB_URL = os.environ.get('MASTER_DB_URL', 'postgresql://postgres@localhost/nexus_autoparts')


def connect():
    return psycopg2.connect(MASTER_DB_URL)


def delete_model_and_myes(conn, model_id):
    cur = conn.cursor()
    cur.execute("SELECT id_mye FROM model_year_engine WHERE model_id = %s", (model_id,))
    mye_ids = [r[0] for r in cur.fetchall()]
    if mye_ids:
        cur.execute("UPDATE supplier_catalog_compat SET model_year_engine_id = NULL WHERE model_year_engine_id = ANY(%s)", (mye_ids,))
        cur.execute("DELETE FROM vin_cache WHERE model_year_engine_id = ANY(%s)", (mye_ids,))
        cur.execute("DELETE FROM model_year_engine WHERE id_mye = ANY(%s)", (mye_ids,))
    cur.execute("DELETE FROM models WHERE id_model = %s", (model_id,))
    cur.close()


def merge_model_to_base(conn, model_id, base_id):
    cur = conn.cursor()
    cur.execute("SELECT id_mye, year_id, engine_id FROM model_year_engine WHERE model_id = %s", (model_id,))
    myes = cur.fetchall()
    migrated = 0
    for mye_id, year_id, engine_id in myes:
        cur.execute("""
            SELECT id_mye FROM model_year_engine
            WHERE model_id = %s AND year_id = %s
            AND (engine_id = %s OR (engine_id IS NULL AND %s IS NULL))
        """, (base_id, year_id, engine_id, engine_id))
        base_mye = cur.fetchone()
        if base_mye:
            cur.execute("UPDATE supplier_catalog_compat SET model_year_engine_id = %s WHERE model_year_engine_id = %s", (base_mye[0], mye_id))
            cur.execute("DELETE FROM vin_cache WHERE model_year_engine_id = %s", (mye_id,))
            cur.execute("DELETE FROM model_year_engine WHERE id_mye = %s", (mye_id,))
        else:
            cur.execute("UPDATE model_year_engine SET model_id = %s WHERE id_mye = %s", (base_id, mye_id))
        migrated += 1
    cur.execute("DELETE FROM models WHERE id_model = %s", (model_id,))
    cur.close()
    return migrated


def main():
    dry_run = '--execute' not in sys.argv
    if dry_run:
        print("=" * 60)
        print("DRY RUN MODE — no changes will be made")
        print("Run with --execute to apply changes")
        print("=" * 60)

    conn = connect()
    cur = conn.cursor()

    # Exact (brand, model_name) pairs to delete
    delete_exact = [
        ('ISUZU', '1.9L 81 - 86 Pick-Up'),
        ('ISUZU', '2.2L 98 - 02 L4 2.3L Turbo 84 - 87'),
        ('ISUZU', '2.2L 98 - 99 L4 Amigo'),
        ('ISUZU', '2.3L 81 - 95 2.0L Turbo 84 - 87'),
        ('ISUZU', '2.3L 81 - 95 Pick-Up'),
        ('ISUZU', '3.2L 92 - 93 V6'),
        ('ISUZU', '3.2L 92 - 93 V6 2.3L Turbo 84 - 87'),
        ('CHEVROLET', '2.0L 1984 L4'),
        ('CHEVROLET', '2.0L 83 - 84 L4'),
        ('CHEVROLET', '2.0L 83 - 84 L4 Jimmy'),
        ('CHEVROLET', '2.8L 1984 V6'),
        ('CHEVROLET', '2.8L 85 - 93 V6'),
        ('CHEVROLET', '3.1L 91 - 95 V6'),
        ('CHEVROLET', '3.1L 91 - 98 V6'),
        ('CHEVROLET', '4.1L 81 - 84 L6'),
        ('CHEVROLET', '4.1L 81 - 84 L6 10'),
        ('CHEVROLET', '4.3L 10'),
        ('CHEVROLET', '4.3L 90 - 93 V6'),
        ('CHEVROLET', '4.3L 90 - 93 V6 10'),
        ('CHEVROLET', '4.3L 96 - 00 V6 10'),
        ('CHEVROLET', '5.0L 96 - 98 V8'),
        ('CHEVROLET', '5.0L 96 - 98 V8 10'),
        ('CHEVROLET', '5.1L 82 - 91 V8'),
        ('CHEVROLET', '5.7L (19.15 mm)'),
        ('CHEVROLET', '5.7L 10'),
        ('CHEVROLET', '5.7L 69 - 91 V8'),
        ('CHEVROLET', '5.7L 69 - 91 V8 10'),
        ('CHRYSLER / DODGE', '2.5L Chasis Cabina'),
        ('CHRYSLER / DODGE', '3.7L 10'),
        ('CHRYSLER / DODGE', '3.7L 86 - 87 L6 23'),
        ('CHRYSLER / DODGE', '3.9L 88 - 91 V6'),
        ('CHRYSLER / DODGE', '3.9L 88 - 91 V6 23'),
        ('CHRYSLER / DODGE', '4.7L 04 - 05 V8'),
        ('CHRYSLER / DODGE', '4.7L 04 - 05 V8 10'),
        ('CHRYSLER / DODGE', '4.7L 10'),
        ('CHRYSLER / DODGE', '5.2L 10'),
        ('CHRYSLER / DODGE', '5.2L 85 - 93 V8'),
        ('CHRYSLER / DODGE', '5.7L 10'),
        ('CHRYSLER / DODGE', '5.9L 10'),
        ('CHRYSLER / DODGE', '5.9L 19'),
        ('CHRYSLER / DODGE', '5.9L 1992 V8 19'),
        ('CHRYSLER / DODGE', '5.9L 88 - 91 V8 19'),
        ('CHRYSLER / DODGE', '5.9L 94 - 97 V8 Ram 7000'),
        ('FORD', '2.0L 97 - 03 L4'),
        ('FORD', '2.0L 97 - 03 L4 10'),
        ('FORD', '2.0L LX, SE'),
        ('FORD', '2.3L 87 - 88 L4'),
        ('FORD', '2.3L 87 - 88 L4 10'),
        ('FORD', '2.3L 87 - 88 L4 Aerostar'),
        ('FORD', '2.3L 87 - 88 L4 Bronco'),
        ('FORD', '3.0L 98 - 01 V6'),
        ('FORD', '4.0L 93 - 97 V6'),
        ('FORD', '4.6L 10'),
        ('FORD', '4.9L 83 - 93 L6 10'),
        ('FORD', '4.9L 88 - 89 L6'),
        ('FORD', '4.9L 88 - 92 L6 10'),
        ('FORD', '5.0L 10'),
        ('FORD', '5.0L 65 - 91 V8 10'),
        ('FORD', '5.0L 88 - 89 V8 10'),
        ('FORD', '5.7L 65 - 84 V8'),
        ('FORD', '5.8L 10'),
        ('FORD', '5.8L 1992 10'),
        ('JEEP', '4.0L 10'),
        ('JEEP', '4.0L 14'),
        ('JEEP', '4.0L 19'),
        ('JEEP', '4.0L 1”'),
        ('JEEP', '4.2L 87 - 89 L6 10'),
        ('JEEP', '4.2L 87 - 89 L6 14'),
        ('NISSAN', '2.4L 85 - 92 L4'),
        ('NISSAN', '2.4L 85 - 92 L4 2.0L 720 74 - 83 L4, L20B, Z22, SD22'),
        ('NISSAN', '2.4L 85 - 92 L4 2.4L 91 - 00 L4, D21'),
        ('NISSAN', '3.0L 89 - 94 Micra'),
        ('NISSAN', '3.0L 89 - 94 NX Coupé DE'),
        ('MAZDA', '4.0L B4000'),
        ('PONTIAC', '5.7L 1998 V8'),
        ('VW', '1.6L (23.40 mm)'),
        ('AUDI', '1.4L TFSI (17.0 mm)'),
        ('BMW', 'Q60 14-16 Sin Paq. Sport'),
        ('MERCEDES BENZ', 'Cayenne Turbo 05-10 R-19”'),
        ('MERCEDES BENZ', 'ne S 05-10 R-19”'),
        ('DODGE', 'Sienna 11-19 Lexux NX200t 15-'),
        ('PEUGEOT', '406 00-05 4Cil.'),
        ('PEUGEOT', 'RAV-4 06-18 Nacio-'),
        ('TOYOTA', 'Sonic RS 12-17 Che-'),
        ('SEAT', 'Ibiza 18. Volkswagen Golf 17-18 9193-D1968 SG'),
    ]

    # (brand, bad_model, base_model)
    merge_map = [
        ('KIA', 'Sorento 14-16 Latino', 'SORENTO'),
        ('HYUNDAI', 'IX20 11-16 Latino', 'ix20 (JC)'),
        ('TOYOTA', 'Corolla CE 07-11 Brasil', 'COROLLA'),
        ('SUZUKI', 'Grand Vitara 09-13 Na-', 'GRAND VITARA'),
        ('CHRYSLER', 'Voyager 00-04 Modelos Europeos', 'VOYAGER'),
    ]

    # Resolve IDs
    to_delete = []
    for bname, mname in delete_exact:
        cur.execute("""
            SELECT b.id_brand, m.id_model
            FROM brands b JOIN models m ON m.brand_id = b.id_brand
            WHERE b.name_brand = %s AND m.name_model = %s
        """, (bname, mname))
        row = cur.fetchone()
        if row:
            to_delete.append((bname, mname, row[1]))

    to_merge = []
    for bname, bad_name, base_name in merge_map:
        cur.execute("""
            SELECT b.id_brand, m.id_model
            FROM brands b JOIN models m ON m.brand_id = b.id_brand
            WHERE b.name_brand = %s AND m.name_model = %s
        """, (bname, bad_name))
        bad = cur.fetchone()
        cur.execute("""
            SELECT m.id_model FROM models m JOIN brands b ON b.id_brand = m.brand_id
            WHERE b.name_brand = %s AND m.name_model = %s
        """, (bname, base_name))
        base = cur.fetchone()
        if bad and base:
            to_merge.append((bname, bad_name, bad[1], base_name, base[0]))

    print(f"\nTo delete: {len(to_delete)}")
    for bname, mname, mid in to_delete:
        print(f"  [{bname}] '{mname}' id={mid}")

    print(f"\nTo merge: {len(to_merge)}")
    for bname, bad_name, mid, base_name, base_id in to_merge:
        print(f"  [{bname}] '{bad_name}' -> '{base_name}'")

    if dry_run:
        print("\n" + "=" * 60)
        print("DRY RUN complete. Run with --execute to apply.")
        print("=" * 60)
        cur.close()
        conn.close()
        return

    print("\nApplying merges...")
    for bname, bad_name, mid, base_name, base_id in to_merge:
        migrated = merge_model_to_base(conn, mid, base_id)
        print(f"  [{bname}] '{bad_name}' -> '{base_name}' ({migrated} MYEs migrated)")
        conn.commit()

    print("\nApplying deletes...")
    for bname, mname, mid in to_delete:
        delete_model_and_myes(conn, mid)
        print(f"  [{bname}] '{mname}' deleted")
        conn.commit()

    print(f"\nDone. Merged {len(to_merge)}, deleted {len(to_delete)}.")
    cur.close()
    conn.close()


if __name__ == '__main__':
    main()
