#!/usr/bin/env python3
"""
IMPORTADOR DEL CATÁLOGO DAR "LÍNEA AZUL" 2020
Formato: Brand → Model → AÑO DESCRIPCIÓN SKU #PÁG
Pages 27-571 contain vehicle application data.
PDF: /tmp/catalogs/suspension/catalogo_azul_2020.pdf
"""

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

DB_PATH = Path(__file__).parent.parent / 'vehicle_database.db'
PDF_PATH = '/tmp/catalogs/suspension/catalogo_azul_2020.pdf'

# Page range (0-indexed) for vehicle application data
START_PAGE = 27
END_PAGE = 571

# Known brand headers in the DAR catalog
DAR_BRANDS = {
    'ACURA', 'ALFA ROMEO', 'AUDI', 'BMW', 'BUICK', 'CADILLAC',
    'CHEVROLET, GMC', 'CHRYSLER', 'DATSUN', 'DODGE', 'EAGLE',
    'FIAT', 'FORD, MERCURY', 'GEO', 'HONDA', 'HUMMER', 'HYUNDAI',
    'INFINITI', 'ISUZU', 'JAGUAR', 'JEEP', 'KIA',
    'LAND ROVER', 'LEXUS', 'LINCOLN', 'MAZDA', 'MERCEDES-BENZ',
    'MERKUR', 'MINI', 'MITSUBISHI', 'NISSAN', 'OLDSMOBILE',
    'OPEL', 'PEUGEOT', 'PLYMOUTH', 'PONTIAC', 'PORSCHE',
    'RAM', 'RENAULT', 'SAAB', 'SATURN', 'SCION', 'SEAT', 'SMART',
    'SUBARU', 'SUZUKI', 'TOYOTA', 'TRIUMPH', 'VOLKSWAGEN',
    'VOLVO', 'VOLVO/MASA',
}

# Year range regex: 2-digit or 4-digit years, or TODOS
YEAR_RE = re.compile(r'^(\d{2,4})\s*-\s*(\d{2,4})\b')
YEAR_SINGLE_RE = re.compile(r'^(\d{2,4})\b')
TODOS_RE = re.compile(r'^TODOS\b', re.IGNORECASE)

# Line ending with SKU + page ref: ...SKU_TOKEN  3-4_DIGIT_PAGEREF
ENTRY_END_RE = re.compile(r'^(.+?)\s+(\S+)\s+(\d{3,4})\s*$')

# Skip patterns
SKIP_PATTERNS = [
    'Línea Azul',
    'CATALOGO AZUL',
    'AÑO DESCRIPCIÓN SKU #PÁG',
    'AÑO DESCRIPCIÓN SKU',
    '.indb',
]


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


def ensure_manufacturer(cursor, name, type_='aftermarket', quality='standard', 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):
    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_description(cursor, desc):
    """Map DAR description text to a DB group_id."""
    d = desc.upper()

    # Amortiguadores (Shocks)
    if 'AMORTIGUADOR' in d and 'BASE' not in d:
        if 'CAJUELA' in d or 'COFRE' in d or 'VIDRIO' in d:
            return get_group_id(cursor, 'Struts')  # trunk/hood/glass struts
        if 'DIRECCIÓN' in d or 'DIRECCION' in d:
            return get_group_id(cursor, 'Steering Dampers')
        return get_group_id(cursor, 'Shocks')

    # Base amortiguador (Strut Mounts)
    if 'BASE AMORTIGUADOR' in d:
        return get_group_id(cursor, 'Strut Mounts')

    # Balero (Bearings)
    if 'BALERO' in d:
        return get_group_id(cursor, 'Wheel Bearings')

    # Maza (Wheel Hubs)
    if 'MAZA' in d:
        return get_group_id(cursor, 'Wheel Hubs')

    # Soporte de Motor / Transmisión (Mounts)
    if 'SOPORTE DE MOTOR' in d or 'SOPORTE MOTOR' in d:
        return get_group_id(cursor, 'Engine Mounts')
    if 'SOPORTE DE TRANSMIS' in d or 'SOPORTE TRANSMIS' in d:
        return get_group_id(cursor, 'Transmission Mounts')
    if 'SOPORTE' in d and 'AMORTIGUADOR' in d:
        return get_group_id(cursor, 'Strut Mounts')
    if 'SOPORTE BRAZO' in d:
        return get_group_id(cursor, 'Idler Arms')

    # Rotula (Ball Joint)
    if 'RÓTULA' in d or 'ROTULA' in d:
        return get_group_id(cursor, 'Ball Joints')

    # Terminal exterior / dirección (Tie Rod Ends)
    if 'TERMINAL EXTERIOR' in d or 'TERMINAL DIREC' in d:
        return get_group_id(cursor, 'Tie Rod Ends')

    # Terminal interior (Inner Tie Rods)
    if 'TERMINAL INTERIOR' in d:
        return get_group_id(cursor, 'Inner Tie Rods')

    # Horquilla (Control Arms)
    if 'HORQUILLA' in d:
        return get_group_id(cursor, 'Control Arms')

    # Buje de varilla estabilizadora
    if 'GOMA' in d and 'ESTABILIZADORA' in d:
        return get_group_id(cursor, 'Sway Bar Bushings')
    if 'BUJE' in d and 'ESTABILIZADORA' in d:
        return get_group_id(cursor, 'Sway Bar Bushings')

    # Tornillo estabilizador (Sway Bar Links)
    if 'TORNILLO ESTABILIZADOR' in d:
        return get_group_id(cursor, 'Sway Bar Links')

    # Buje (Bushings)
    if 'BUJE' in d:
        return get_group_id(cursor, 'Bushings')

    # Resorte (Springs)
    if 'RESORTE' in d:
        return get_group_id(cursor, 'Coil Springs')

    # Brazo auxiliar (Idler Arm)
    if 'BRAZO AUXILIAR' in d:
        return get_group_id(cursor, 'Idler Arms')

    # Brazo Pitman
    if 'BRAZO PITMAN' in d or 'PITMAN' in d:
        return get_group_id(cursor, 'Pitman Arms')

    # Varilla / Barra central (Center Links)
    if 'BARRA CENTRAL' in d or 'VARILLA CENTRAL' in d:
        return get_group_id(cursor, 'Center Links')

    # Varilla lateral / Barra de arrastre (Drag Links)
    if 'VARILLA' in d:
        return get_group_id(cursor, 'Drag Links')

    # Cremallera (Steering Rack)
    if 'CREMALLERA' in d:
        return get_group_id(cursor, 'Steering Racks')

    # Bomba dirección (Power Steering Pump)
    if 'BOMBA DIREC' in d:
        return get_group_id(cursor, 'Power Steering Pumps')

    # Cople dirección (Steering Gearbox / Coupling)
    if 'COPLE DIREC' in d:
        return get_group_id(cursor, 'Steering Gearboxes')

    # Flector dirección
    if 'FLECTOR' in d:
        return get_group_id(cursor, 'Steering Gearboxes')

    # Nudo dirección (Steering Knuckle)
    if 'NUDO DIREC' in d:
        return get_group_id(cursor, 'Steering Knuckles')

    # Excéntrico (Camber/Caster)
    if 'EXCÉNTRICO' in d or 'EXCENTRICO' in d or 'CAMBER' in d:
        return get_group_id(cursor, 'Camber/Caster Kits')

    # Junta CV
    if 'JUNTA' in d and ('RUEDA' in d or 'CAJA' in d):
        return get_group_id(cursor, 'CV Joints')

    # Macheta / Flecha
    if 'MACHETA' in d or 'FLECHA' in d:
        return get_group_id(cursor, 'CV Axles')

    # Tirante (Trailing Arm)
    if 'TIRANTE' in d:
        return get_group_id(cursor, 'Trailing Arms')

    # Barra horquilla / Barra torsión
    if 'BARRA' in d and 'TORSIÓN' in d:
        return get_group_id(cursor, 'Torsion Bars')
    if 'BARRA' in d and 'HORQUILLA' in d:
        return get_group_id(cursor, 'Control Arms')

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


# --- Part type name from description ---
def part_names_from_desc(desc, sku):
    """Generate English and Spanish names from DAR description."""
    name_es = f"{desc} {sku}"
    # Simplified English name
    name_en = desc
    for es, en in [
        ('AMORTIGUADOR DELANTERO', 'Front Shock'),
        ('AMORTIGUADOR TRASERO', 'Rear Shock'),
        ('AMORTIGUADOR', 'Shock Absorber'),
        ('BASE AMORTIGUADOR', 'Strut Mount'),
        ('BALERO DOBLE', 'Double Bearing'),
        ('BALERO CONICO', 'Tapered Bearing'),
        ('BALERO', 'Wheel Bearing'),
        ('BOMBA DIREC', 'Power Steering Pump'),
        ('BRAZO AUXILIAR', 'Idler Arm'),
        ('BRAZO PITMAN', 'Pitman Arm'),
        ('BUJE', 'Bushing'),
        ('CREMALLERA', 'Steering Rack'),
        ('COPLE DIREC', 'Steering Coupler'),
        ('FLECTOR', 'Steering Flex Disc'),
        ('GOMA VARILLA ESTABILIZADORA', 'Sway Bar Bushing'),
        ('HORQUILLA INFERIOR', 'Lower Control Arm'),
        ('HORQUILLA SUPERIOR', 'Upper Control Arm'),
        ('HORQUILLA', 'Control Arm'),
        ('MAZA DELANTERA', 'Front Wheel Hub'),
        ('MAZA TRASERA', 'Rear Wheel Hub'),
        ('MAZA', 'Wheel Hub'),
        ('RESORTE DELANTERO', 'Front Coil Spring'),
        ('RESORTE TRASERO', 'Rear Coil Spring'),
        ('RESORTE', 'Coil Spring'),
        ('RÓTULA INFERIOR', 'Lower Ball Joint'),
        ('RÓTULA SUPERIOR', 'Upper Ball Joint'),
        ('ROTULA INFERIOR', 'Lower Ball Joint'),
        ('ROTULA SUPERIOR', 'Upper Ball Joint'),
        ('RÓTULA', 'Ball Joint'),
        ('ROTULA', 'Ball Joint'),
        ('SOPORTE DE MOTOR', 'Engine Mount'),
        ('SOPORTE DE TRANSMIS', 'Transmission Mount'),
        ('TERMINAL EXTERIOR', 'Outer Tie Rod End'),
        ('TERMINAL INTERIOR', 'Inner Tie Rod'),
        ('TERMINAL DIREC', 'Tie Rod End'),
        ('TIRANTE', 'Trailing Arm'),
        ('TORNILLO ESTABILIZADOR', 'Sway Bar Link'),
        ('VARILLA', 'Drag Link'),
        ('EXCÉNTRICO', 'Camber Kit'),
    ]:
        if es in desc.upper():
            name_en = f"{en} {sku}"
            break
    else:
        name_en = f"{desc} {sku}"
    return name_en, name_es


def convert_year(yy):
    """Convert 2-digit year to 4-digit. 00-30 → 2000-2030, 31-99 → 1931-1999."""
    y = int(yy)
    if y >= 100:
        return y  # already 4-digit
    if y <= 30:
        return 2000 + y
    return 1900 + y


def is_skip_line(line):
    for pat in SKIP_PATTERNS:
        if pat in line:
            return True
    # Pure page numbers
    if re.match(r'^\d{1,3}$', line.strip()):
        return True
    return False


def is_brand_line(line):
    """Check if line is a brand header."""
    stripped = line.strip()
    if stripped in DAR_BRANDS:
        return True
    # Some brands have extra whitespace or minor variations
    for b in DAR_BRANDS:
        if stripped.upper() == b:
            return True
    return False


def parse_dar_pdf(pdf_path):
    """Parse the DAR Catalogo Azul vehicle application pages."""
    pdf = pypdf.PdfReader(pdf_path)
    entries = []
    current_brands = []  # List because some pages have "CHEVROLET, GMC"
    current_model = None

    # Accumulator for multi-line entries
    entry_year_from = None
    entry_year_to = None
    entry_lines = []

    def flush_entry():
        nonlocal entry_year_from, entry_year_to, entry_lines
        if not entry_lines or entry_year_from is None:
            entry_lines = []
            entry_year_from = None
            entry_year_to = None
            return

        # Join accumulated lines
        full_text = ' '.join(entry_lines)

        # Try to extract SKU and page ref from the end
        m = ENTRY_END_RE.match(full_text)
        if m:
            desc_text = m.group(1).strip()
            sku = m.group(2).strip()
            # page_ref = m.group(3)  # not used for import

            if sku and desc_text and current_model:
                for brand_name in current_brands:
                    for year in range(entry_year_from, entry_year_to + 1):
                        entries.append({
                            'brand': brand_name,
                            'model': current_model,
                            'year': year,
                            'description': desc_text,
                            'sku': sku,
                        })

        entry_lines = []
        entry_year_from = None
        entry_year_to = None

    for page_num in range(START_PAGE, min(END_PAGE + 1, len(pdf.pages))):
        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

            # Check for brand header
            if is_brand_line(line):
                flush_entry()
                # Split combined brands like "CHEVROLET, GMC"
                current_brands = [b.strip() for b in line.split(',')]
                current_model = None
                continue

            # Check for model line
            # A model line is: not starting with a digit, not a data entry,
            # not a brand, and we already have a brand
            if not current_brands:
                continue

            # Check if this line starts with a year range
            m_year = YEAR_RE.match(line)
            m_single = YEAR_SINGLE_RE.match(line) if not m_year else None
            m_todos = TODOS_RE.match(line)

            if m_year or m_todos:
                # Flush previous entry
                flush_entry()

                if m_todos:
                    # "TODOS" = all years, use a reasonable range
                    entry_year_from = 1960
                    entry_year_to = 2020
                    rest = line[m_todos.end():].strip()
                else:
                    y1 = convert_year(m_year.group(1))
                    y2 = convert_year(m_year.group(2))
                    entry_year_from = min(y1, y2)
                    entry_year_to = max(y1, y2)
                    rest = line[m_year.end():].strip()

                if rest:
                    entry_lines.append(rest)
                continue

            # If we're accumulating an entry, add continuation line
            if entry_year_from is not None:
                entry_lines.append(line)
                continue

            # Check if it's a single year + data (rare)
            if m_single and len(line) > 4:
                y_val = int(m_single.group(1))
                # Only treat as year if it's a plausible 2-digit year (not a 4+ digit number)
                if y_val < 100 and len(m_single.group(1)) == 2:
                    flush_entry()
                    entry_year_from = convert_year(m_single.group(1))
                    entry_year_to = entry_year_from
                    rest = line[m_single.end():].strip()
                    if rest:
                        entry_lines.append(rest)
                    continue

            # If we get here, it's likely a model name
            # Strip "(cont)" suffix
            model_name = re.sub(r'\s*\(cont\)\s*$', '', line, flags=re.IGNORECASE).strip()
            if model_name and not model_name.startswith('AÑO') and len(model_name) > 1:
                flush_entry()
                current_model = model_name

    # Flush last entry
    flush_entry()
    return entries


def main():
    print("=" * 70)
    print("IMPORTADOR - CATÁLOGO DAR 'LÍNEA AZUL' 2020")
    print("=" * 70)

    print(f"\n[1/5] Leyendo PDF: {PDF_PATH}")
    entries = parse_dar_pdf(PDF_PATH)
    print(f"      Entradas parseadas: {len(entries):,}")

    unique_skus = set(e['sku'] for e in entries)
    unique_brands = set(e['brand'] for e in entries)
    unique_models = set((e['brand'], e['model']) for e in entries)
    print(f"      SKUs únicos: {len(unique_skus):,}")
    print(f"      Marcas de vehículos: {len(unique_brands):,}")
    print(f"      Modelos únicos: {len(unique_models):,}")

    # Show sample entries
    print("\n      Primeras 5 entradas:")
    for e in entries[:5]:
        print(f"        {e['brand']} {e['model']} {e['year']} | {e['description']} | {e['sku']}")

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

    # Create DAR manufacturer
    print("\n[2/5] Creando fabricante DAR...")
    dar_mfr_id = ensure_manufacturer(cursor, 'DAR', 'aftermarket', 'standard', 'Mexico')
    print(f"      DAR manufacturer_id: {dar_mfr_id}")

    # Create parts
    print("\n[3/5] Creando partes...")
    part_ids = {}
    parts_created = 0
    for sku in sorted(unique_skus):
        # Find one entry with this SKU to get description
        sample = next(e for e in entries if e['sku'] == sku)
        group_id = classify_description(cursor, sample['description'])
        name_en, name_es = part_names_from_desc(sample['description'], sku)
        part_id, created = get_or_create_part(
            cursor, sku, group_id, name_en, name_es, 'DAR Línea Azul')
        part_ids[sku] = part_id
        if created:
            parts_created += 1

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

    # Create aftermarket entries for DAR-specific parts
    print("      Creando aftermarket entries...")
    am_created = 0
    for sku in sorted(unique_skus):
        part_id = part_ids.get(sku)
        if not part_id:
            continue
        cursor.execute(
            "SELECT id FROM aftermarket_parts WHERE manufacturer_id = ? AND part_number = ?",
            (dar_mfr_id, sku))
        if not cursor.fetchone():
            sample = next(e for e in entries if e['sku'] == sku)
            name_en, name_es = part_names_from_desc(sample['description'], sku)
            cursor.execute(
                "INSERT INTO aftermarket_parts (oem_part_id, manufacturer_id, part_number, name, name_es) VALUES (?, ?, ?, ?, ?)",
                (part_id, dar_mfr_id, sku, name_en, name_es))
            am_created += 1
    print(f"      Aftermarket entries creadas: {am_created:,}")

    # Create vehicles and fitments
    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):,}...")

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

            # Try to find existing MYE
            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""",
                (entry['brand'], 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['sku'])
        if not part_id:
            continue

        # Check if fitment exists
        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"Catálogo DAR Línea Azul 2020"
            if entry.get('description'):
                notes += f" - {entry['description']}"
            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:,}")

    # Cross-references: match DAR parts to MOOG parts on same vehicles
    print("\n[5/5] Creando referencias cruzadas...")
    xrefs_created = 0

    for sku, part_id in part_ids.items():
        # Find other parts (different brand) in same group fitting same vehicles
        cursor.execute("""
            SELECT DISTINCT p2.id, p2.oem_part_number
            FROM vehicle_parts vp1
            JOIN vehicle_parts vp2 ON vp1.model_year_engine_id = vp2.model_year_engine_id
            JOIN parts p2 ON vp2.part_id = p2.id
            WHERE vp1.part_id = ?
              AND p2.id != ?
              AND p2.group_id = (SELECT group_id FROM parts WHERE id = ?)
              AND p2.oem_part_number != ?
            LIMIT 30
        """, (part_id, part_id, part_id, sku))

        for row in cursor.fetchall():
            other_pn = row['oem_part_number']
            # Skip if same part number prefix pattern (same brand)
            if other_pn[:3] == sku[:3]:
                continue

            # A -> B
            cursor.execute(
                "SELECT id FROM part_cross_references WHERE part_id = ? AND cross_reference_number = ?",
                (part_id, other_pn))
            if not cursor.fetchone():
                cursor.execute(
                    "INSERT INTO part_cross_references (part_id, cross_reference_number, reference_type, source) VALUES (?, ?, 'interchange', 'DAR Catalog')",
                    (part_id, other_pn))
                xrefs_created += 1

            # B -> A
            cursor.execute(
                "SELECT id FROM part_cross_references WHERE part_id = ? AND cross_reference_number = ?",
                (row['id'], sku))
            if not cursor.fetchone():
                cursor.execute(
                    "INSERT INTO part_cross_references (part_id, cross_reference_number, reference_type, source) VALUES (?, ?, 'interchange', 'DAR Catalog')",
                    (row['id'], sku))
                xrefs_created += 1

    print(f"      Cross-refs creadas: {xrefs_created:,}")

    conn.commit()
    conn.close()

    print("\n" + "=" * 70)
    print("IMPORTACIÓN DAR COMPLETADA")
    print("=" * 70)
    print(f"""
RESUMEN:
  - Partes creadas:        {parts_created:,}
  - Aftermarket entries:   {am_created:,}
  - Vehículos creados:     {vehicles_created:,}
  - Fitments creados:      {fitments_created:,}
  - Cross-refs creadas:    {xrefs_created:,}
""")


if __name__ == '__main__':
    main()
