#!/usr/bin/env python3
"""
Import Gonher Filter Catalog PDF into the autoparts database.
Extracts filter part numbers and vehicle compatibility.
"""

import sqlite3
import re
import pypdf
from pathlib import Path

# Database path
DB_PATH = Path(__file__).parent.parent / 'vehicle_database.db'
PDF_PATH = '/tmp/filtros_catalog.pdf'

# Filter type mapping
FILTER_TYPES = {
    'ACEITE': {'category': 'Engine', 'group': 'Oil Filters', 'name_prefix': 'Oil Filter'},
    'SINTÉTICO': {'category': 'Engine', 'group': 'Oil Filters', 'name_prefix': 'Synthetic Oil Filter'},
    'AIRE': {'category': 'Engine', 'group': 'Air Filters', 'name_prefix': 'Air Filter'},
    'COMB.': {'category': 'Fuel & Air', 'group': 'Fuel Filters', 'name_prefix': 'Fuel Filter'},
    'CABINA': {'category': 'Heat & Air Conditioning', 'group': 'Cabin Air Filters', 'name_prefix': 'Cabin Air Filter'}
}

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

def ensure_manufacturer(cursor, name='Gonher'):
    """Ensure Gonher manufacturer exists"""
    cursor.execute("SELECT id FROM manufacturers WHERE name = ?", (name,))
    row = cursor.fetchone()
    if row:
        return row['id']

    cursor.execute("""
        INSERT INTO manufacturers (name, type, quality_tier, country)
        VALUES (?, 'aftermarket', 'standard', 'Mexico')
    """, (name,))
    return cursor.lastrowid

def get_or_create_group(cursor, category_name, group_name):
    """Get or create a part group"""
    # Find category
    cursor.execute("SELECT id FROM part_categories WHERE name = ?", (category_name,))
    cat_row = cursor.fetchone()
    if not cat_row:
        print(f"  Warning: Category '{category_name}' not found")
        return None

    category_id = cat_row['id']

    # Find or create group
    cursor.execute("""
        SELECT id FROM part_groups
        WHERE category_id = ? AND name = ?
    """, (category_id, group_name))
    group_row = cursor.fetchone()

    if group_row:
        return group_row['id']

    # Create group
    cursor.execute("""
        INSERT INTO part_groups (category_id, name, name_es)
        VALUES (?, ?, ?)
    """, (category_id, group_name, group_name))
    return cursor.lastrowid

def parse_year_range(year_str):
    """Parse year range like '2019 - 2016' or '2020- 2018' into list of years"""
    year_str = year_str.strip()

    # Handle single year
    if re.match(r'^\d{4}$', year_str):
        return [int(year_str)]

    # Handle range with various separators
    match = re.match(r'(\d{4})\s*[-–]\s*(\d{4})', year_str)
    if match:
        start, end = int(match.group(1)), int(match.group(2))
        if start > end:
            start, end = end, start
        return list(range(end, start + 1))

    return []

def parse_catalog_page(text, current_brand=None):
    """Parse a catalog page and extract vehicle-filter mappings"""
    entries = []
    lines = text.split('\n')

    brand = current_brand
    model = None

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

        # Skip header lines
        if 'AÑO' in line and 'MOTOR' in line:
            continue
        if 'ACEITE' in line and 'AIRE' in line:
            continue
        if 'Los filtros Gonher' in line:
            continue
        if 'Para vehículos anteriores' in line:
            continue
        if '(Continúa)' in line:
            # Extract brand/model from continuation
            match = re.match(r'^([A-Z\s]+)\s*\(Continúa\)', line)
            if match:
                potential = match.group(1).strip()
                if len(potential) > 2:
                    if potential in ['ACURA', 'ALFA ROMEO', 'AUDI', 'BMW', 'BUICK', 'CADILLAC',
                                     'CHEVROLET', 'CHRYSLER', 'DODGE', 'FIAT', 'FORD', 'GMC',
                                     'HONDA', 'HYUNDAI', 'INFINITI', 'JAGUAR', 'JEEP', 'KIA',
                                     'LEXUS', 'LINCOLN', 'MAZDA', 'MERCEDES BENZ', 'MERCURY',
                                     'MINI', 'MITSUBISHI', 'NISSAN', 'PEUGEOT', 'PONTIAC',
                                     'PORSCHE', 'RAM', 'RENAULT', 'SEAT', 'SMART', 'SUBARU',
                                     'SUZUKI', 'TOYOTA', 'VOLKSWAGEN', 'VOLVO']:
                        brand = potential
                    else:
                        model = potential
            continue

        # Check if this is a brand line (all caps, single word or known brand)
        if re.match(r'^[A-Z][A-Z\s]+$', line) and len(line) > 2:
            potential_brand = line.strip()
            if potential_brand in ['ACURA', 'ALFA ROMEO', 'AUDI', 'BMW', 'BUICK', 'CADILLAC',
                                   'CHEVROLET', 'CHRYSLER', 'DODGE', 'FIAT', 'FORD', 'GMC',
                                   'HONDA', 'HYUNDAI', 'INFINITI', 'JAGUAR', 'JEEP', 'KIA',
                                   'LEXUS', 'LINCOLN', 'MAZDA', 'MERCEDES BENZ', 'MERCURY',
                                   'MINI', 'MITSUBISHI', 'NISSAN', 'PEUGEOT', 'PONTIAC',
                                   'PORSCHE', 'RAM', 'RENAULT', 'SEAT', 'SMART', 'SUBARU',
                                   'SUZUKI', 'TOYOTA', 'VOLKSWAGEN', 'VOLVO']:
                brand = potential_brand
                model = None
                continue

        # Check if this is a model line (letters/numbers, no year pattern at start)
        if brand and re.match(r'^[A-Z][A-Z0-9\s\-]+$', line) and not re.match(r'^\d{4}', line):
            if not any(c.isdigit() for c in line[:4]):  # Model names don't start with 4 digits
                potential_model = line.strip()
                if len(potential_model) >= 2 and potential_model not in ['ACEITE', 'AIRE', 'COMB', 'CABINA']:
                    model = potential_model
                    continue

        # Try to parse data line (year, motor, filters)
        # Pattern: YEAR[-YEAR] MOTOR FILTER1 FILTER2 ...
        if brand and model:
            # Look for year at start
            match = re.match(r'^(\d{4}(?:\s*[-–]\s*\d{4})?)\s+(.+)$', line)
            if match:
                year_str = match.group(1)
                rest = match.group(2)

                # Extract motor (usually like L4-2.0L or V6-3.5L)
                motor_match = re.match(r'^([LV]\d+[-][\d.]+L(?:\s+(?:Turbo|TURBOCHARGED|diésel|ELECTRIC))?)\s*(.*)$', rest, re.IGNORECASE)
                if motor_match:
                    motor = motor_match.group(1).strip()
                    filters_str = motor_match.group(2).strip()

                    # Parse filter part numbers
                    # They follow pattern like: GP-149 GPS-149 GA-1113 GAC-92
                    filter_parts = re.findall(r'[A-Z]+[-][\dA-Z]+(?:\(\d+\))?', filters_str)

                    years = parse_year_range(year_str)

                    if years and filter_parts:
                        for year in years:
                            entry = {
                                'brand': brand,
                                'model': model,
                                'year': year,
                                'motor': motor,
                                'filters': {}
                            }

                            # Categorize filters by prefix
                            for fp in filter_parts:
                                fp_clean = re.sub(r'\(\d+\)', '', fp)  # Remove (1) markers
                                if fp_clean.startswith('GP-') or fp_clean.startswith('G-'):
                                    entry['filters']['ACEITE'] = fp_clean
                                elif fp_clean.startswith('GPS-'):
                                    entry['filters']['SINTÉTICO'] = fp_clean
                                elif fp_clean.startswith('GA-') and not fp_clean.startswith('GAC-') and not fp_clean.startswith('GAVW-'):
                                    entry['filters']['AIRE'] = fp_clean
                                elif fp_clean.startswith('GG-'):
                                    entry['filters']['COMB.'] = fp_clean
                                elif fp_clean.startswith('GAC-'):
                                    entry['filters']['CABINA'] = fp_clean

                            if entry['filters']:
                                entries.append(entry)

    return entries, brand

def import_catalog():
    """Main import function"""
    print("="*60)
    print("GONHER FILTER CATALOG IMPORT")
    print("="*60)

    # Read PDF
    print(f"\nReading PDF: {PDF_PATH}")
    pdf = pypdf.PdfReader(PDF_PATH)
    total_pages = len(pdf.pages)
    print(f"Total pages: {total_pages}")

    # Parse all pages
    all_entries = []
    current_brand = None

    for i in range(total_pages):
        text = pdf.pages[i].extract_text()
        if text:
            entries, current_brand = parse_catalog_page(text, current_brand)
            all_entries.extend(entries)

        if (i + 1) % 20 == 0:
            print(f"  Processed {i + 1}/{total_pages} pages, {len(all_entries)} entries so far...")

    print(f"\nTotal entries extracted: {len(all_entries)}")

    # Get unique filters
    unique_filters = {}
    for entry in all_entries:
        for filter_type, part_num in entry['filters'].items():
            if part_num not in unique_filters:
                unique_filters[part_num] = filter_type

    print(f"Unique filter part numbers: {len(unique_filters)}")

    # Import to database
    conn = get_db_connection()
    cursor = conn.cursor()

    # Ensure Gonher manufacturer exists
    manufacturer_id = ensure_manufacturer(cursor, 'Gonher')
    print(f"\nManufacturer ID: {manufacturer_id}")

    # Create parts for each unique filter
    print("\nCreating filter parts...")
    filter_part_ids = {}

    for part_num, filter_type in unique_filters.items():
        config = FILTER_TYPES.get(filter_type)
        if not config:
            continue

        group_id = get_or_create_group(cursor, config['category'], config['group'])
        if not group_id:
            continue

        # Check if part exists
        cursor.execute("SELECT id FROM parts WHERE oem_part_number = ?", (part_num,))
        existing = cursor.fetchone()

        if existing:
            filter_part_ids[part_num] = existing['id']
        else:
            # Create new part
            name = f"{config['name_prefix']} {part_num}"
            name_es = f"Filtro {part_num}"

            cursor.execute("""
                INSERT INTO parts (oem_part_number, name, name_es, group_id, description)
                VALUES (?, ?, ?, ?, ?)
            """, (part_num, name, name_es, group_id, f"Gonher {config['name_prefix']}"))

            filter_part_ids[part_num] = cursor.lastrowid

    print(f"  Created/found {len(filter_part_ids)} filter parts")

    # Create vehicle fitments
    print("\nCreating vehicle fitments...")
    fitments_created = 0
    fitments_skipped = 0

    for entry in all_entries:
        # Find matching vehicle (model_year_engine)
        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']))

        mye_row = cursor.fetchone()
        if not mye_row:
            fitments_skipped += 1
            continue

        mye_id = mye_row['id']

        # Create fitments for each filter
        for filter_type, part_num in entry['filters'].items():
            part_id = filter_part_ids.get(part_num)
            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():
                cursor.execute("""
                    INSERT INTO vehicle_parts (model_year_engine_id, part_id, quantity_required, fitment_notes)
                    VALUES (?, ?, 1, ?)
                """, (mye_id, part_id, f"Gonher catalog 2022 - {filter_type}"))
                fitments_created += 1

    print(f"  Fitments created: {fitments_created}")
    print(f"  Entries skipped (vehicle not found): {fitments_skipped}")

    conn.commit()
    conn.close()

    print("\n" + "="*60)
    print("IMPORT COMPLETE")
    print("="*60)

    return {
        'total_entries': len(all_entries),
        'unique_filters': len(unique_filters),
        'parts_created': len(filter_part_ids),
        'fitments_created': fitments_created
    }

if __name__ == '__main__':
    results = import_catalog()
    print(f"\nSummary: {results}")
