#!/usr/bin/env python3
"""
Second pass: clean remaining supplier-corrupted models.
More aggressive patterns for engine specs mixed with years.

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

import os
import re
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 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()

    # Aggressive patterns for remaining garbage
    # Pattern: starts with displacement and contains year range or engine config
    patterns = [
        re.compile(r'^\d+\.\d+L.*\d{2}-\d{2}', re.IGNORECASE),  # 2.2L 98-99 L4 Amigo
        re.compile(r'^\d+\.\d+L\s+[A-Za-z].*L\d', re.IGNORECASE),  # 1.5L March
        re.compile(r'^\d+\.\d+L\s+[A-Za-z]{3,}$', re.IGNORECASE),  # 1.8L R
        re.compile(r'^\d+\.\d+L\s+Datsun', re.IGNORECASE),  # 1.5L Datsun 1600
        re.compile(r'\d{2}-\d{2}.*L4,', re.IGNORECASE),  # ...98-99...L4,
        re.compile(r'\d{2}-\d{2}.*\d+\.\d+L.*Gasolina', re.IGNORECASE),  # ...07-16...2.4L Gasolina
        re.compile(r'^370 Z\s+\d+\.\d+L', re.IGNORECASE),  # 370 Z 1.5L
        re.compile(r'Brakes.*\d{2}-\d{2}', re.IGNORECASE),  # Cooper JC Works Brakes 09-15
        re.compile(r'Cabstar.*\d{2}-\d{2}', re.IGNORECASE),  # Cabstar 3.5T 07-16
        re.compile(r'X Terra.*Chevrolet', re.IGNORECASE),  # X Terra 05-15 Chevrolet City
    ]

    # Specific known-bad models by exact name
    known_bad = {
        '1.8L R', '2.5L 08 - 13', 'Eclipse 2.0L Aspiración Natural',
        'Cooper JC Works Brakes 09-15 Disco de 316mm',
        'Cabstar 3.5T 07-16 C/Sensor', 'X Terra 05-15 Chevrolet City Ex-',
        'NP-300 (D-22) 2WD 2.4L GASOLINA', 'NV-350 2.5L GAS',
    }

    cur.execute('SELECT id_model, name_model, brand_id FROM models')
    models = cur.fetchall()

    to_delete = []
    for mid, name, bid in models:
        if not name:
            continue
        n = name.strip()
        if n in known_bad:
            to_delete.append((bid, n, mid, 'known_bad'))
            continue
        for pat in patterns:
            if pat.search(n):
                # Exclude legitimate TecDoc patterns like "1100-1900 (101_)"
                if re.search(r'^\d{4}-\d{4} \([A-Z0-9_]+\)$', n):
                    continue
                to_delete.append((bid, n, mid, 'pattern'))
                break

    print(f"\nFound {len(to_delete)} remaining corrupted models")
    for bid, n, mid, reason in to_delete:
        cur.execute('SELECT name_brand FROM brands WHERE id_brand=%s', (bid,))
        bname = cur.fetchone()[0]
        cur.execute('SELECT COUNT(*) FROM model_year_engine WHERE model_id=%s', (mid,))
        mye_count = cur.fetchone()[0]
        print(f"  [{bname}] '{n}' id={mid} MYEs={mye_count} reason={reason}")

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

    print("\nApplying deletes...")
    for bid, n, mid, reason in to_delete:
        cur.execute('SELECT name_brand FROM brands WHERE id_brand=%s', (bid,))
        bname = cur.fetchone()[0]
        delete_model_and_myes(conn, mid)
        print(f"  [{bname}] '{n}' deleted")
        conn.commit()

    print(f"\nDone. Deleted {len(to_delete)} models.")
    cur.close()
    conn.close()


if __name__ == '__main__':
    main()
