#!/usr/bin/env python3
"""
IMPORTADOR DEL CATÁLOGO MOOG - SUSPENSIÓN Y DIRECCIÓN
Funciona para los 3 volúmenes:
  Vol 1: ≤1989   /tmp/catalogs/suspension/moog_vol1_1989back.pdf   pages 4-1037
  Vol 2: 1990-2005 /tmp/catalogs/suspension/moog_vol2_1990_2005.pdf pages 7-1641
  Vol 3: 2006+   /tmp/catalogs/suspension/moog_vol3_2006up.pdf     pages 8-1089
"""

import sqlite3
import re
import sys
import pypdf
from pathlib import Path
from collections import defaultdict

DB_PATH = Path(__file__).parent.parent / 'vehicle_database.db'

VOLUMES = {
    '1': {
        'path': '/tmp/catalogs/suspension/moog_vol1_1989back.pdf',
        'start_page': 3,   # 0-indexed
        'end_page': 1037,
        'label': 'Vol 1 (≤1989)',
    },
    '2': {
        'path': '/tmp/catalogs/suspension/moog_vol2_1990_2005.pdf',
        'start_page': 6,
        'end_page': 1641,
        'label': 'Vol 2 (1990-2005)',
    },
    '3': {
        'path': '/tmp/catalogs/suspension/moog_vol3_2006up.pdf',
        'start_page': 7,
        'end_page': 1089,
        'label': 'Vol 3 (2006+)',
    },
}

MOOG_BRANDS = {
    'ACURA', 'ALFA ROMEO', 'AMERICAN MOTORS', 'AMERICAN MOTORS CORP.',
    'ASTON MARTIN', 'AUDI', 'BMW', 'BUICK', 'CADILLAC',
    'CHEVROLET', 'CHEVROLET TRUCK', 'CHRYSLER',
    'DATSUN', 'DODGE', 'DODGE TRUCK',
    'EAGLE', 'FIAT', 'FORD', 'FORD TRUCK', 'FREIGHTLINER',
    'GEO', 'GEO TRUCK', 'GENERAL MOTORS TRUCK',
    'HONDA', 'HUMMER', 'HYUNDAI',
    'INFINITI', 'INTERNATIONAL', 'ISUZU', 'ISUZU TRUCK',
    'JAGUAR', 'JEEP', 'KIA',
    'LAFORZA', 'LAND ROVER', 'LEXUS', 'LINCOLN', 'LOTUS',
    'MAZDA', 'MAZDA TRUCK', 'MERCEDES BENZ', 'MERCEDES-BENZ',
    'MERCURY', 'MERKUR', 'MINI', 'MITSUBISHI', 'MITSUBISHI TRUCK',
    'NISSAN', 'NISSAN TRUCK',
    'OLDSMOBILE', 'OPEL',
    'PEUGEOT', 'PLYMOUTH', 'PLYMOUTH TRUCK', 'PONTIAC', 'PORSCHE',
    'RAM TRUCK', 'RENAULT', 'ROLLS ROYCE',
    'SAAB', 'SATURN', 'SCION', 'SEAT', 'SHELBY', 'SMART', 'STERLING',
    'SUBARU', 'SUBARU TRUCK', 'SUZUKI', 'SUZUKI TRUCK',
    'TOYOTA', 'TOYOTA TRUCK', 'TRIUMPH',
    'VOLKSWAGEN', 'VOLKSWAGEN TRUCK', 'VOLVO', 'VOLVO TRUCK',
    'WILLYS MOTORS INC.',
}

# MOOG part number regex
MOOG_PART_RE = re.compile(
    r'\b(K\d{3,7}T?|ES\d{3,7}[A-Z]{0,3}T?|EV\d{3,7}[A-Z]?|DS\d{3,7}'
    r'|CC\d{3,6}|CK\d{3,7}|SSD\d{2,4}|BK\d{3,4}[A-Z]?'
    r'|SB\d{3,4}|NIBJ\d+|VO[A-Z]{2}\d+|HY[A-Z]{2}\d+|AU[A-Z]{2}\d+|BM[A-Z]{2}\d+)\b'
)

# Numeric-only springs (only used within spring category context)
SPRING_NUM_RE = re.compile(r'\b(\d{4,6})\b')

# Figure code
FIGURE_RE = re.compile(r'\b([FSR]\d{3})\b')

# Year range at start of line
YEAR_RE = re.compile(r'^(\d{4})(?:\s*-\s*(\d{4}))?')

# System sections
SYSTEM_PATTERNS = {
    'SUSPENSION DELANTERA': 'front_suspension',
    'SUSPENSIÓN DELANTERA': 'front_suspension',
    'DIRECCIÓN': 'steering',
    'DIRECCION': 'steering',
    'SUSPENSION TRASERA': 'rear_suspension',
    'SUSPENSIÓN TRASERA': 'rear_suspension',
}

# Header/footer markers to skip
SKIP_MARKERS = [
    'www.moogproblemsolver.com',
    'CATÁLOGO MASTER',
    'CATALOGO MASTER',
    'Solucionador de problemas',
    'búsqueda de piezas electrónicas',
    'FMe-cat.mx',
    'Año Observaciones',
    'Total Solución',
    'P/C\nCTD',
    'Imagenes de piezas',
]


def get_db():
    conn = sqlite3.connect(DB_PATH)
    conn.row_factory = sqlite3.Row
    return conn


def ensure_manufacturer(cursor, name, type_='aftermarket', quality='premium', country=None):
    cursor.execute("SELECT id FROM manufacturers WHERE UPPER(name) = UPPER(?)", (name,))
    row = cursor.fetchone()
    if row:
        return row['id']
    cursor.execute(
        "INSERT INTO manufacturers (name, type, quality_tier, country) VALUES (?, ?, ?, ?)",
        (name, type_, quality, country))
    return cursor.lastrowid


def ensure_brand(cursor, name):
    cursor.execute("SELECT id FROM brands WHERE UPPER(name) = UPPER(?)", (name,))
    row = cursor.fetchone()
    if row:
        return row['id']
    cursor.execute("INSERT INTO brands (name) VALUES (?)", (name,))
    return cursor.lastrowid


def ensure_model(cursor, brand_id, name):
    cursor.execute(
        "SELECT id FROM models WHERE brand_id = ? AND UPPER(name) = UPPER(?)",
        (brand_id, name))
    row = cursor.fetchone()
    if row:
        return row['id']
    cursor.execute("INSERT INTO models (brand_id, name) VALUES (?, ?)", (brand_id, name))
    return cursor.lastrowid


def ensure_year(cursor, year):
    cursor.execute("SELECT id FROM years WHERE year = ?", (year,))
    row = cursor.fetchone()
    if row:
        return row['id']
    cursor.execute("INSERT INTO years (year) VALUES (?)", (year,))
    return cursor.lastrowid


def get_generic_engine(cursor):
    cursor.execute("SELECT id FROM engines WHERE name = 'Generic'")
    row = cursor.fetchone()
    if row:
        return row['id']
    cursor.execute("INSERT INTO engines (name, fuel_type) VALUES ('Generic', 'gasoline')")
    return cursor.lastrowid


def ensure_mye(cursor, model_id, year_id, engine_id=None):
    if engine_id:
        cursor.execute(
            "SELECT id FROM model_year_engine WHERE model_id = ? AND year_id = ? AND engine_id = ?",
            (model_id, year_id, engine_id))
    else:
        cursor.execute(
            "SELECT id FROM model_year_engine WHERE model_id = ? AND year_id = ?",
            (model_id, year_id))
    row = cursor.fetchone()
    if row:
        return row['id']
    if not engine_id:
        engine_id = get_generic_engine(cursor)
    cursor.execute(
        "INSERT INTO model_year_engine (model_id, year_id, engine_id) VALUES (?, ?, ?)",
        (model_id, year_id, engine_id))
    return cursor.lastrowid


def get_or_create_part(cursor, part_number, group_id, name, name_es, description):
    cursor.execute("SELECT id FROM parts WHERE oem_part_number = ?", (part_number,))
    row = cursor.fetchone()
    if row:
        return row['id'], False
    cursor.execute(
        "INSERT INTO parts (oem_part_number, name, name_es, group_id, description) VALUES (?, ?, ?, ?, ?)",
        (part_number, name, name_es, group_id, description))
    return cursor.lastrowid, True


# --- Group ID lookup cache ---
_group_cache = {}


def get_group_id(cursor, name_en):
    """Get group ID by English name."""
    if name_en not in _group_cache:
        cursor.execute("SELECT id FROM part_groups WHERE name = ?", (name_en,))
        row = cursor.fetchone()
        _group_cache[name_en] = row['id'] if row else None
    return _group_cache[name_en]


def classify_part(cursor, category_text, part_number):
    """Map MOOG category text + part number to a DB group_id."""
    cat = category_text.lower() if category_text else ''

    # By category text (Spanish)
    if 'rótula' in cat and 'suspensión' in cat:
        return get_group_id(cursor, 'Ball Joints')
    if 'rótula' in cat and 'prensad' in cat:
        return get_group_id(cursor, 'Ball Joints')
    if 'brazo de control' in cat and 'rótula' in cat:
        return get_group_id(cursor, 'Control Arms')
    if 'ensamble de brazo' in cat:
        return get_group_id(cursor, 'Control Arms')
    if 'brazo de control' in cat:
        return get_group_id(cursor, 'Control Arms')
    if 'horquilla' in cat:
        return get_group_id(cursor, 'Control Arms')
    if 'buje' in cat and 'estabilizadora' in cat:
        return get_group_id(cursor, 'Sway Bar Bushings')
    if 'buje' in cat and 'brazo' in cat:
        return get_group_id(cursor, 'Bushings')
    if 'buje' in cat and 'amortiguador' in cat:
        return get_group_id(cursor, 'Bushings')
    if 'buje' in cat and 'tracción' in cat:
        return get_group_id(cursor, 'Bushings')
    if 'buje' in cat and 'camber' in cat:
        return get_group_id(cursor, 'Camber/Caster Kits')
    if 'buje' in cat:
        return get_group_id(cursor, 'Bushings')
    if 'cople' in cat and 'estabilizadora' in cat:
        return get_group_id(cursor, 'Sway Bar Links')
    if 'soporte' in cat and ('strut' in cat.lower() or 'amortiguador' in cat):
        return get_group_id(cursor, 'Strut Mounts')
    if 'montaje' in cat and 'amortiguador' in cat:
        return get_group_id(cursor, 'Strut Mounts')
    if 'fuelle' in cat or 'cubrepolvo' in cat:
        return get_group_id(cursor, 'Struts')
    if 'asiento' in cat and 'resorte' in cat:
        return get_group_id(cursor, 'Spring Seats')
    if 'ensamble de terminal' in cat:
        return get_group_id(cursor, 'Tie Rod Ends')
    if 'terminal' in cat and 'dirección' in cat:
        if part_number and part_number.startswith('EV'):
            return get_group_id(cursor, 'Inner Tie Rods')
        return get_group_id(cursor, 'Tie Rod Ends')
    if 'barra central' in cat:
        return get_group_id(cursor, 'Center Links')
    if 'barra de arrastre' in cat or 'barra de acoplamiento' in cat:
        return get_group_id(cursor, 'Drag Links')
    if 'varilla de dirección' in cat:
        return get_group_id(cursor, 'Drag Links')
    if 'resorte' in cat and 'suspensión' in cat:
        return get_group_id(cursor, 'Coil Springs')
    if 'camber' in cat or 'caster' in cat:
        return get_group_id(cursor, 'Camber/Caster Kits')
    if 'brazo auxiliar' in cat or 'brazo loco' in cat:
        return get_group_id(cursor, 'Idler Arms')
    if 'brazo pitman' in cat:
        return get_group_id(cursor, 'Pitman Arms')
    if 'amortiguador de dirección' in cat:
        return get_group_id(cursor, 'Steering Dampers')
    if 'pasador' in cat and 'dirección' in cat:
        return get_group_id(cursor, 'King Pin Sets')
    if 'muelle' in cat:
        return get_group_id(cursor, 'Leaf Springs')
    if 'barra de torsión' in cat:
        return get_group_id(cursor, 'Torsion Bars')

    # Fallback by part prefix
    if part_number:
        if part_number.startswith('ES'):
            return get_group_id(cursor, 'Tie Rod Ends')
        if part_number.startswith('EV'):
            return get_group_id(cursor, 'Inner Tie Rods')
        if part_number.startswith('DS'):
            return get_group_id(cursor, 'Center Links')
        if part_number.startswith('CC') or (part_number.isdigit() and len(part_number) >= 4):
            return get_group_id(cursor, 'Coil Springs')
        if part_number.startswith('SSD'):
            return get_group_id(cursor, 'Steering Dampers')
        if part_number.startswith('CK'):
            return get_group_id(cursor, 'Control Arms')
        if part_number.startswith('BK'):
            return get_group_id(cursor, 'King Pin Sets')
        if part_number.startswith('SB'):
            return get_group_id(cursor, 'Bushings')

    return get_group_id(cursor, 'Ball Joints')  # Default


# --- Part type names for DB ---

PART_TYPE_NAMES = {
    'Ball Joints': ('Ball Joint', 'Rótula de Suspensión'),
    'Bushings': ('Bushing', 'Buje'),
    'Sway Bar Bushings': ('Sway Bar Bushing', 'Buje de Barra Estabilizadora'),
    'Control Arms': ('Control Arm', 'Brazo de Control'),
    'Sway Bar Links': ('Sway Bar Link', 'Cople de Barra Estabilizadora'),
    'Strut Mounts': ('Strut Mount', 'Soporte de Strut'),
    'Struts': ('Strut Boot', 'Fuelle de Strut'),
    'Spring Seats': ('Spring Seat', 'Asiento de Resorte'),
    'Tie Rod Ends': ('Tie Rod End', 'Terminal de Dirección'),
    'Inner Tie Rods': ('Inner Tie Rod', 'Terminal Interior de Dirección'),
    'Center Links': ('Center Link', 'Barra Central'),
    'Drag Links': ('Drag Link', 'Barra de Arrastre'),
    'Coil Springs': ('Coil Spring', 'Resorte Helicoidal'),
    'Camber/Caster Kits': ('Camber/Caster Kit', 'Kit de Camber/Caster'),
    'Idler Arms': ('Idler Arm', 'Brazo Auxiliar'),
    'Pitman Arms': ('Pitman Arm', 'Brazo Pitman'),
    'Steering Dampers': ('Steering Damper', 'Amortiguador de Dirección'),
    'King Pin Sets': ('King Pin Set', 'Juego de Pivote'),
    'Leaf Springs': ('Leaf Spring', 'Muelle'),
    'Torsion Bars': ('Torsion Bar', 'Barra de Torsión'),
}


# --- Parsing ---

def is_skip_line(line):
    """Check if line is header/footer to skip."""
    return any(m in line for m in SKIP_MARKERS)


def parse_brand_model(line):
    """Try to parse a brand-model line. Returns (brand, model) or (None, None)."""
    for dash in ['−', '–', '—', '-']:
        if dash not in line:
            continue
        parts = line.split(dash, 1)
        if len(parts) != 2:
            continue
        left = re.sub(r'\s*\(Cont\.?\)\.?\s*', '', parts[0]).strip()
        right = re.sub(r'\s*\(Cont\.?\)\.?\s*', '', parts[1]).strip()
        if not left or not right:
            continue

        left_up = left.upper()
        right_up = right.upper()

        # Check which side matches a known brand
        for brand in MOOG_BRANDS:
            if left_up == brand or left_up.startswith(brand + ' '):
                return left, right
            if right_up == brand or right_up.startswith(brand + ' '):
                return right, left

        # Heuristic: if left is all uppercase words and right has mixed case
        if left.isupper() and len(left) > 2:
            return left, right
        if right.isupper() and len(right) > 2:
            return right, left

    return None, None


def detect_system(line):
    """Check if line is a system section header."""
    clean = line.strip().upper()
    for pattern, system in SYSTEM_PATTERNS.items():
        if clean.startswith(pattern.upper()):
            return system
    return None


CATEGORY_KEYWORDS = [
    'Rótula', 'Rotula', 'Buje', 'Brazo de control', 'Brazo auxiliar',
    'Brazo pitman', 'Brazo loco', 'Cople', 'Soporte', 'Fuelle',
    'Asiento del resorte', 'Terminal de dirección', 'Terminal de direccion',
    'Ensamble de terminal', 'Ensamble de brazo', 'Barra central',
    'Barra de arrastre', 'Barra de dirección', 'Varilla',
    'Juego de resortes', 'Resorte de suspensión', 'Juego para ajuste',
    'Placa para ajuste', 'Seguro guia', 'Amortiguador de dirección',
    'Pasador de dirección', 'Horquilla', 'Muelle',
    'Juego de coples', 'Juego de soporte', 'Juego de montaje',
    'Montaje del amortiguador',
]


def is_category_line(line):
    """Check if line is a part category header."""
    for kw in CATEGORY_KEYWORDS:
        if kw.lower() in line.lower():
            # Make sure it doesn't also contain a part number (data line)
            if not MOOG_PART_RE.search(line):
                return True
    return False


def parse_moog_pdf(pdf_path, start_page, end_page):
    """Parse a MOOG catalog PDF and return entries."""
    pdf = pypdf.PdfReader(pdf_path)
    entries = []

    current_brand = None
    current_model = None
    current_submodel = None
    current_system = None
    current_figure = None
    current_category = None
    current_year_from = None
    current_year_to = None

    total = min(len(pdf.pages), end_page)

    for page_num in range(start_page, total):
        if (page_num - start_page) % 100 == 0:
            print(f"      Página {page_num + 1}/{total}...")

        text = pdf.pages[page_num].extract_text()
        if not text:
            continue

        lines = text.split('\n')

        for line in lines:
            line = line.strip()
            if not line:
                continue
            if is_skip_line(line):
                continue

            # Skip standalone page numbers
            if re.match(r'^\d{1,4}$', line) and not current_category:
                continue

            # Brand-model line
            brand, model = parse_brand_model(line)
            if brand and model:
                current_brand = brand
                current_model = model
                current_submodel = None
                current_system = None
                current_figure = None
                current_category = None
                continue

            # System section
            system = detect_system(line)
            if system:
                current_system = system
                current_category = None
                current_submodel = None
                # Check for figure code on same line or next
                fig = FIGURE_RE.search(line)
                if fig:
                    current_figure = fig.group(1)
                continue

            # Standalone figure code line
            fig_match = re.match(r'^([FSR]\d{3})$', line.strip())
            if fig_match:
                current_figure = fig_match.group(1)
                continue

            # Figure code with comma (e.g., "F530,\nF531")
            fig_multi = re.match(r'^([FSR]\d{3}),?$', line.strip())
            if fig_multi and not YEAR_RE.match(line):
                current_figure = fig_multi.group(1)
                continue

            if not current_brand or not current_model:
                continue

            # Part category header
            if is_category_line(line):
                current_category = line.strip()
                continue

            # Data line with year
            year_match = YEAR_RE.match(line)
            if year_match:
                y1 = int(year_match.group(1))
                y2 = int(year_match.group(2)) if year_match.group(2) else y1
                if 1930 <= y1 <= 2025 and 1930 <= y2 <= 2025:
                    current_year_from = min(y1, y2)
                    current_year_to = max(y1, y2)

            # Extract MOOG part numbers from line
            parts_found = MOOG_PART_RE.findall(line)

            # Also check for numeric springs in spring context
            if current_category and 'resorte' in current_category.lower():
                for m in SPRING_NUM_RE.finditer(line):
                    num = m.group(1)
                    if len(num) >= 4 and not any(num == p for p in parts_found):
                        # Avoid matching years
                        n = int(num)
                        if not (1930 <= n <= 2025):
                            parts_found.append(num)

            if not parts_found or not current_year_from:
                continue

            # Build entries for each part found
            model_name = current_model
            if current_submodel:
                model_name = f"{current_model} {current_submodel}"

            for pn in parts_found:
                # Clean part number (remove trailing T for Problem Solver)
                clean_pn = pn.rstrip('T') if pn.endswith('T') and len(pn) > 4 else pn

                for year in range(current_year_from, current_year_to + 1):
                    entries.append({
                        'brand': current_brand,
                        'model': model_name,
                        'year': year,
                        'system': current_system or 'front_suspension',
                        'figure': current_figure,
                        'category': current_category or '',
                        'part_number': clean_pn,
                        'notes': line.strip(),
                    })

    return entries


def normalize_brand(brand):
    """Normalize MOOG brand names to standard form."""
    mappings = {
        'CHEVROLET TRUCK': 'CHEVROLET',
        'DODGE TRUCK': 'DODGE',
        'FORD TRUCK': 'FORD',
        'GENERAL MOTORS TRUCK': 'GMC',
        'GEO TRUCK': 'GEO',
        'ISUZU TRUCK': 'ISUZU',
        'MAZDA TRUCK': 'MAZDA',
        'MITSUBISHI TRUCK': 'MITSUBISHI',
        'NISSAN TRUCK': 'NISSAN',
        'PLYMOUTH TRUCK': 'PLYMOUTH',
        'SUBARU TRUCK': 'SUBARU',
        'SUZUKI TRUCK': 'SUZUKI',
        'TOYOTA TRUCK': 'TOYOTA',
        'VOLKSWAGEN TRUCK': 'VOLKSWAGEN',
        'VOLVO TRUCK': 'VOLVO',
        'AMERICAN MOTORS CORP.': 'AMERICAN MOTORS',
        'AMERICAN MOTORS': 'AMERICAN MOTORS',
        'MERCEDES BENZ': 'MERCEDES-BENZ',
        'WILLYS MOTORS INC.': 'WILLYS',
        'RAM TRUCK': 'RAM',
    }
    up = brand.upper().strip()
    return mappings.get(up, brand.strip())


def main():
    if len(sys.argv) < 2 or sys.argv[1] not in VOLUMES:
        print("Uso: python3 import_moog_catalog.py <1|2|3>")
        print("  1 = Vol 1 (≤1989)")
        print("  2 = Vol 2 (1990-2005)")
        print("  3 = Vol 3 (2006+)")
        sys.exit(1)

    vol = sys.argv[1]
    config = VOLUMES[vol]

    print("=" * 70)
    print(f"IMPORTADOR - CATÁLOGO MOOG {config['label']}")
    print("=" * 70)

    print(f"\n[1/5] Leyendo PDF: {config['path']}")
    entries = parse_moog_pdf(config['path'], config['start_page'], config['end_page'])
    print(f"      Entradas parseadas: {len(entries):,}")

    unique_parts = {}
    for e in entries:
        if e['part_number'] not in unique_parts:
            unique_parts[e['part_number']] = e['category']

    unique_brands = set(normalize_brand(e['brand']) for e in entries)
    print(f"      Partes únicas: {len(unique_parts):,}")
    print(f"      Marcas de vehículos: {len(unique_brands)}")

    conn = get_db()
    cursor = conn.cursor()

    print("\n[2/5] Creando fabricante MOOG...")
    moog_mfr_id = ensure_manufacturer(cursor, 'MOOG', 'aftermarket', 'premium', 'USA')
    print(f"      MOOG manufacturer_id: {moog_mfr_id}")

    print("\n[3/5] Creando partes...")
    part_ids = {}
    parts_created = 0

    for pn, cat_text in sorted(unique_parts.items()):
        group_id = classify_part(cursor, cat_text, pn)
        if not group_id:
            group_id = get_group_id(cursor, 'Ball Joints')

        # Get group name for part description
        cursor.execute("SELECT name FROM part_groups WHERE id = ?", (group_id,))
        group_row = cursor.fetchone()
        group_name = group_row['name'] if group_row else 'Suspension Part'

        names = PART_TYPE_NAMES.get(group_name, (group_name, group_name))
        name_en = f"{names[0]} {pn}"
        name_es = f"{names[1]} {pn}"

        part_id, created = get_or_create_part(
            cursor, pn, group_id, name_en, name_es, f"MOOG {names[0]}")
        part_ids[pn] = part_id
        if created:
            parts_created += 1

    print(f"      Partes creadas: {parts_created:,}")
    print(f"      Partes existentes: {len(unique_parts) - parts_created:,}")

    print("\n[4/5] Creando vehículos y fitments...")
    vehicles_created = 0
    fitments_created = 0
    mye_cache = {}

    for i, entry in enumerate(entries):
        if i % 10000 == 0 and i > 0:
            print(f"      Procesando {i:,}/{len(entries):,}...")

        brand_name = normalize_brand(entry['brand'])
        cache_key = (brand_name.upper(), entry['model'].upper(), entry['year'])

        if cache_key not in mye_cache:
            brand_id = ensure_brand(cursor, brand_name)
            model_id = ensure_model(cursor, brand_id, entry['model'])
            year_id = ensure_year(cursor, entry['year'])

            cursor.execute("""
                SELECT mye.id FROM model_year_engine mye
                JOIN models m ON mye.model_id = m.id
                JOIN brands b ON m.brand_id = b.id
                JOIN years y ON mye.year_id = y.id
                WHERE UPPER(b.name) = UPPER(?) AND UPPER(m.name) = UPPER(?) AND y.year = ?
                LIMIT 1
            """, (brand_name, entry['model'], entry['year']))
            existing = cursor.fetchone()

            if existing:
                mye_cache[cache_key] = existing['id']
            else:
                mye_id = ensure_mye(cursor, model_id, year_id)
                mye_cache[cache_key] = mye_id
                vehicles_created += 1

        mye_id = mye_cache[cache_key]
        part_id = part_ids.get(entry['part_number'])
        if not part_id:
            continue

        cursor.execute(
            "SELECT id FROM vehicle_parts WHERE model_year_engine_id = ? AND part_id = ?",
            (mye_id, part_id))
        if not cursor.fetchone():
            notes = f"MOOG Catalog {config['label']}"
            if entry['figure']:
                notes += f" - Fig {entry['figure']}"
            if entry['system']:
                notes += f" - {entry['system']}"
            cursor.execute(
                "INSERT INTO vehicle_parts (model_year_engine_id, part_id, quantity_required, fitment_notes) VALUES (?, ?, 1, ?)",
                (mye_id, part_id, notes))
            fitments_created += 1

    print(f"      Vehículos creados: {vehicles_created:,}")
    print(f"      Fitments creados: {fitments_created:,}")

    # Store diagram references
    print("\n[5/5] Guardando referencias de diagramas...")
    figures_seen = set()
    # Get a default group_id for diagrams
    susp_group = get_group_id(cursor, 'Ball Joints') or 164
    for entry in entries:
        if entry['figure'] and entry['figure'] not in figures_seen:
            figures_seen.add(entry['figure'])
            cursor.execute("SELECT id FROM diagrams WHERE name = ?", (entry['figure'],))
            if not cursor.fetchone():
                sys_label = {
                    'front_suspension': 'Suspensión Delantera',
                    'steering': 'Dirección',
                    'rear_suspension': 'Suspensión Trasera',
                }.get(entry.get('system'), 'Suspensión')
                cursor.execute(
                    "INSERT INTO diagrams (name, name_es, group_id, image_path, source) VALUES (?, ?, ?, ?, ?)",
                    (entry['figure'], f"MOOG {sys_label} - {entry['figure']}",
                     susp_group, f"moog/{entry['figure']}.png", 'MOOG Catalog'))

    print(f"      Diagramas registrados: {len(figures_seen)}")

    conn.commit()
    conn.close()

    print("\n" + "=" * 70)
    print(f"IMPORTACIÓN MOOG {config['label']} COMPLETADA")
    print("=" * 70)
    print(f"""
RESUMEN:
  - Partes creadas:        {parts_created:,}
  - Vehículos creados:     {vehicles_created:,}
  - Fitments creados:      {fitments_created:,}
  - Diagramas:             {len(figures_seen)}
""")


if __name__ == '__main__':
    main()
