#!/usr/bin/env python3
"""Final wave: delete remaining engine-displacement models left by supplier imports.

These are not real models (e.g. '5.7L 85 - 96 V8', '7.4L 73 - 91 V8', '5.8L 93 - 96 V8').
Deleting them removes fake MYEs; compat rows are unlinked (model_year_engine_id=NULL)
and remain searchable by SKU / part number.
"""
import argparse
import os

import psycopg2

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

# Remaining engine-pattern models after v3 cleanup.
ENGINE_PATTERN_MODELS = [
    # Chevrolet
    ("CHEVROLET", "5.7L 85 - 96 V8"),
    ("CHEVROLET", "5.7L 85 - 96 V8 Yukon"),
    ("CHEVROLET", "5.7L 99 - 00 V8"),
    ("CHEVROLET", "5.7L P-300 85 - 98 V8 10"),
    ("CHEVROLET", "7.4L 73 - 91 V8"),
    ("CHEVROLET", "7.4L 73 - 91 V8 10"),
    ("CHEVROLET", "7.4L 85 - 95 V8"),
    ("CHEVROLET", "7.4L 85 - 95 V8 10"),
    ("CHEVROLET", "7.4L 87 - 91 V8"),
    ("CHEVROLET", "7.4L 87 - 91 V8 10"),
    # Ford
    ("FORD", "5.8L 1998 V8"),
    ("FORD", "5.8L 1998 V8 10"),
    ("FORD", "5.8L 84 - 87 V8"),
    ("FORD", "5.8L 84 - 87 V8 10"),
    ("FORD", "5.8L 84 - 87 V8 Pro"),
    ("FORD", "5.8L 88 - 89 V8"),
    ("FORD", "5.8L 88 - 95 V8 10"),
    ("FORD", "5.8L 89 - 91 V8"),
    ("FORD", "5.8L 93 - 96 V8"),
    ("FORD", "5.8L XLT 91 - 97 V8"),
    ("FORD", "6.2L 10"),
    ("FORD", "6.8L XL Super Duty 05 - 06"),
    ("FORD", "6.8L XL Super Duty 05 - 06 10"),
    ("FORD", "7.3L 1994 V8, FI, Turbo Diesel"),
    ("FORD", "7.3L 94 - 98 10"),
    # Toyota
    ("TOYOTA", "2.2L 74 - 80 L4, 20R Engine"),
]


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 main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--execute", action="store_true")
    args = parser.parse_args()

    if not args.execute:
        print("=" * 60)
        print("DRY RUN MODE — no changes will be made")
        print("Run with --execute to apply changes")
        print("=" * 60)

    conn = psycopg2.connect(MASTER_DB_URL)
    conn.autocommit = False
    cur = conn.cursor()

    to_delete = []
    for brand_name, model_name in ENGINE_PATTERN_MODELS:
        cur.execute(
            """
            SELECT m.id_model, b.name_brand, m.name_model
            FROM models m
            JOIN brands b ON b.id_brand = m.brand_id
            WHERE UPPER(b.name_brand) = %s AND m.name_model = %s
            """,
            (brand_name, model_name),
        )
        row = cur.fetchone()
        if row:
            to_delete.append(row)
        else:
            print(f"  NOT FOUND: [{brand_name}] {model_name!r}")

    print(f"\nTo delete: {len(to_delete)}")
    total_myes = 0
    for mid, bname, mname in to_delete:
        cur.execute("SELECT COUNT(*) FROM model_year_engine WHERE model_id = %s", (mid,))
        cnt = cur.fetchone()[0]
        total_myes += cnt
        print(f"  [{bname}] {mname!r} id={mid} MYEs={cnt}")

    print(f"Total MYEs to remove: {total_myes}")

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

    for mid, bname, mname in to_delete:
        delete_model_and_myes(conn, mid)
        print(f"  Deleted [{bname}] {mname!r}")

    conn.commit()
    print(f"\nDone. Deleted {len(to_delete)} models ({total_myes} MYEs removed).")

    cur.close()
    conn.close()


if __name__ == "__main__":
    main()
