#!/usr/bin/env python3
"""
Import Fiat Ducato VAN MY26 into SSY demo DB from the CH DE price list PDF.

Source: Preisliste_Ducato_VAN_MY26_DE_062026.pdf (+ curated options JSON).
Does NOT read astara_pdb / PCM.

Usage:
  python storage/app/import_ducato_from_pdf.py --replace
"""
from __future__ import annotations

import json
import re
import sys
from decimal import Decimal
from pathlib import Path
from typing import Any

import pymysql

HOST = "192.168.200.4"
PORT = 3307
USER = "developer"
PASSWORD = "DEVEL!now1"
DST_DB = "astara_pdb_demo_hy"

HERE = Path(__file__).resolve().parent
DEFAULT_PDF = HERE / "Preisliste_Ducato_VAN_MY26_DE_062026.pdf"
DEFAULT_TXT = HERE / "Preisliste_Ducato_VAN_MY26_DE_062026.txt"
DEFAULT_OPTIONS = HERE / "ducato_van_my26_options.json"

MODEL_CODE = "DUC"
MODEL_NAME = "Ducato"
WEBSITE_MODEL = "ducato"
MODEL_YEAR = 2026

FOOTER_DE = (
    "1) Unverbindliche Preisempfehlung des Herstellers ab Werk, Preise ohne MwSt.\n"
    "2) Vorläufige Werte (inkl. Fahrer 75 kg).\n"
    "3) ICE: Euro 6e-ISC-FCM. Quelle: Preisliste Ducato VAN MY26 DE 06.2026."
)

SINCOM_RE = re.compile(
    r"(?m)^(?P<sincom>(?:290|295|505)\.[A-Z0-9]+\.\d+)\s+"
    r"(?P<size>L\dH\d)\s+"
    r"(?P<rest>.+?)\s+"
    r"(?P<price>\d{1,3}(?:['\u2019]\d{3})+(?:\.\d+)?|\d+(?:\.\d+)?)\s*$"
)


def log(msg: str) -> None:
    print(msg, flush=True)


def connect() -> pymysql.connections.Connection:
    return pymysql.connect(
        host=HOST,
        port=PORT,
        user=USER,
        password=PASSWORD,
        database=DST_DB,
        charset="utf8mb4",
        autocommit=False,
    )


def max_id(cur: pymysql.cursors.Cursor, table: str, column: str) -> int:
    cur.execute(f"SELECT COALESCE(MAX(`{column}`), 0) FROM `{table}`")
    return int(cur.fetchone()[0])


def clip(value: str | None, max_len: int) -> str | None:
    if value is None:
        return None
    return value[:max_len]


def normalize_number_token(token: str) -> str:
    return token.replace("\u2019", "'").replace("'", "").replace(" ", "")


def parse_price(token: str) -> Decimal:
    return Decimal(normalize_number_token(token))


def parse_int_token(token: str) -> int | None:
    cleaned = normalize_number_token(token)
    if not cleaned:
        return None
    try:
        return int(float(cleaned))
    except ValueError:
        return None


def parse_decimal_token(token: str) -> Decimal | None:
    cleaned = normalize_number_token(token).replace(",", ".")
    if not cleaned:
        return None
    try:
        return Decimal(cleaned)
    except Exception:
        return None


def first_number(text: str) -> Decimal | None:
    match = re.search(r"\d+(?:[.,]\d+)?", text.replace("'", "").replace("\u2019", ""))
    if not match:
        return None
    return parse_decimal_token(match.group(0))


def detect_glass(section: str) -> str:
    s = section.lower()
    if "teilverglast" in s or "t. verglast" in s or "t.-verglast" in s or "semi-vitr" in s or "semivetr" in s:
        return "t-verglast"
    if "verglast" in s or "vitr" in s:
        return "verglast"
    return "verblecht"


def detect_maxi(section: str) -> bool:
    return "maxi" in section.lower()


def extract_pdf_text(pdf_path: Path) -> str:
    from pypdf import PdfReader

    reader = PdfReader(str(pdf_path))
    parts: list[str] = []
    for i, page in enumerate(reader.pages):
        parts.append(f"---PAGE {i + 1}---\n{(page.extract_text() or '')}")
    return "\n".join(parts)


def load_source_text(pdf_path: Path | None, txt_path: Path | None) -> str:
    if txt_path and txt_path.exists():
        log(f"  reading text: {txt_path}")
        return txt_path.read_text(encoding="utf-8")
    if pdf_path and pdf_path.exists():
        log(f"  extracting PDF: {pdf_path}")
        text = extract_pdf_text(pdf_path)
        DEFAULT_TXT.write_text(text, encoding="utf-8")
        log(f"  wrote cache text: {DEFAULT_TXT}")
        return text
    raise FileNotFoundError("Need PDF or extracted .txt next to the importer")


def parse_price_rows(text: str) -> list[dict[str, Any]]:
    rows: list[dict[str, Any]] = []
    section = "Kastenwagen verblecht"
    for raw_line in text.splitlines():
        line = raw_line.strip()
        if not line:
            continue
        low = line.lower()
        if "kastenwagen" in low or "furgone" in low or "fourgon" in low:
            if any(x in low for x in ("verblech", "verglast", "vitr", "tôlé", "tole", "lastrat")):
                section = line
                continue

        match = SINCOM_RE.match(line)
        if not match:
            continue

        sincom = match.group("sincom")
        size = match.group("size")
        rest = match.group("rest")
        price = parse_price(match.group("price"))
        tokens = rest.split()

        is_bev = sincom.startswith("505.") or "BEV" in tokens
        power_kw = power_ps = None
        for i, tok in enumerate(tokens):
            if tok.isdigit() and i + 1 < len(tokens) and tokens[i + 1].startswith("("):
                power_kw = int(tok)
                ps_match = re.search(r"\((\d+)\)", tokens[i + 1])
                if ps_match:
                    power_ps = int(ps_match.group(1))
                break
        if is_bev:
            power_kw = power_kw or 210
            power_ps = power_ps or 270

        gearbox = "AT" if is_bev else "MT"
        for tok in tokens:
            if tok.startswith("AT"):
                gearbox = "AT"
                break
            if tok.startswith("MT"):
                gearbox = "MT"
                break

        # zGG is the last large integer among 3000/3300/3500/4250-ish before price.
        zgg = None
        for tok in reversed(tokens):
            val = parse_int_token(tok)
            if val in {3000, 3300, 3500, 4250}:
                zgg = val
                break
            if val and 2500 <= val <= 5000 and val % 50 == 0:
                zgg = val
                break
        if zgg is None:
            zgg = 3500

        glass = detect_glass(section)
        maxi = detect_maxi(section) or sincom.startswith("295.")

        # Consumption / CO2: take first decimal-ish after gearbox token for consumption,
        # and first 3-digit int for ICE CO2; BEV uses kWh figure after AT.
        consumption = None
        co2 = None
        if is_bev:
            for tok in tokens:
                if re.fullmatch(r"\d+[.,]\d+", tok):
                    consumption = parse_decimal_token(tok)
                    break
            co2 = 0
        else:
            # Find MT6/AT8 index then scan following tokens for patterns like 7.3 or 193
            gb_idx = next((i for i, t in enumerate(tokens) if t.startswith(("MT", "AT"))), -1)
            after = tokens[gb_idx + 1 :] if gb_idx >= 0 else tokens
            for tok in after:
                if re.fullmatch(r"\d+[.,]\d+", tok) and consumption is None:
                    consumption = parse_decimal_token(tok)
                val = parse_int_token(tok)
                if val and 80 <= val <= 400 and co2 is None and consumption is not None:
                    # Prefer values after benzinaquivalent range; first 3-digit after consumption often CO2 start
                    if val >= 150:
                        co2 = val
                        break

        # PDF trim axis = glass type only (Kastenwagen / teilverglast / vollverglast).
        # LxHx, zGG, Maxi stay on the set (price row), not as separate trims.
        trim_name = {
            "verblecht": "Kastenwagen",
            "t-verglast": "Kastenwagen teilverglast",
            "verglast": "Kastenwagen vollverglast",
        }[glass]

        if is_bev:
            engine_key = "bev_210_270"
            engine_name = "Elektromotor 210 kW | 270 PS - Batterie 110 kWh"
            fuel = "electric"
            emission_class = None
            displacement = 0.0
        else:
            engine_key = f"diesel_{power_kw}_{power_ps}"
            engine_name = f"2.2 Multijet {power_kw} kW | {power_ps} PS"
            fuel = "diesel"
            emission_class = "E6E"
            displacement = 2.2

        bt_row = {"size": size, "maxi": maxi, "zgg": zgg}
        rows.append(
            {
                "sincom": sincom,
                "size": size,
                "glass": glass,
                "maxi": maxi,
                "zgg": zgg,
                "wersja_name": trim_name,
                "bodytype_name": bodytype_label(bt_row),
                "bodytype_code": bodytype_code(bt_row),
                "engine_key": engine_key,
                "engine_name": engine_name,
                "fuel": fuel,
                "power_kw": power_kw or 0,
                "power_ps": power_ps or 0,
                "displacement": displacement,
                "emission_class": emission_class,
                "gearbox": gearbox,
                "consumption": consumption,
                "co2": co2,
                "price": price,
                "is_bev": is_bev,
            }
        )
    return rows


def availability_to_relacja(flag: str) -> int:
    """PDF legend → Equipment (wyp2set) relacja: N=-1, O=0, S=1."""
    flag = (flag or "O").upper().strip()
    flag = flag.split("/")[0]
    if flag == "S":
        return 1
    if flag == "N":
        return -1
    return 0  # O = optional


GLASS_FLAG_KEY = {
    "verblecht": "verblecht",
    "t-verglast": "t_verglast",
    "verglast": "verglast",
}


def trim_has_fuel(fuel: str, wersja_id: int, set_rows_meta: list[dict[str, Any]]) -> bool:
    fuel = fuel or "all"
    for row in set_rows_meta:
        if row["wersja_id"] != wersja_id:
            continue
        if fuel == "all":
            return True
        if fuel == "bev" and row["is_bev"]:
            return True
        if fuel == "ice" and not row["is_bev"]:
            return True
    return False


def equipment_relacja(
    item: dict[str, Any],
    glass: str,
    wersja_id: int,
    set_rows_meta: list[dict[str, Any]],
) -> int:
    """Resolve O/S/N for one equipment row × trim (glass)."""
    if not trim_has_fuel(item.get("fuel", "all"), wersja_id, set_rows_meta):
        return -1
    flag_key = GLASS_FLAG_KEY[glass]
    # Sonderausstattung (and any serie row with explicit glass flags)
    if any(k in item for k in ("verblecht", "t_verglast", "verglast")):
        return availability_to_relacja(item.get(flag_key, "O"))
    # Pure Serienausstattung without matrix → Standard when fuel matches
    return 1


def unique_code(base: str, used: set[str], width: int = 6) -> str:
    cleaned = re.sub(r"[^A-Za-z0-9]", "", base or "X").upper() or "X"
    code = cleaned[:width].ljust(min(3, width), "X")[:width]
    if code not in used:
        used.add(code)
        return code
    for n in range(1, 10000):
        candidate = f"{cleaned[: max(1, width - 2)]}{n:02d}"[:width]
        if candidate not in used:
            used.add(candidate)
            return candidate
    raise RuntimeError(f"Cannot allocate code for {base!r}")


def bodytype_label(row: dict[str, Any]) -> str:
    """LxHx [| Maxi] | N.N t — visible dimension separate from glass-type trim."""
    tons = f"{row['zgg'] / 1000:g} t"
    parts = [row["size"]]
    if row.get("maxi"):
        parts.append("Maxi")
    parts.append(tons)
    return " | ".join(parts)


def bodytype_code(row: dict[str, Any]) -> str:
    base = row["size"]
    if row.get("maxi"):
        base += "MX"
    base += str(row["zgg"])
    return re.sub(r"[^A-Za-z0-9]", "", base)[:6].upper()


def ensure_bodytype_schema(cur: pymysql.cursors.Cursor) -> None:
    cur.execute("SHOW TABLES LIKE 'con_bodytypes'")
    if not cur.fetchone():
        cur.execute(
            """
            CREATE TABLE `con_bodytypes` (
              `id_bodytypes` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
              `bodytype` varchar(64) DEFAULT NULL,
              `code` varchar(6) DEFAULT NULL,
              `lp` int(11) NOT NULL DEFAULT 99,
              PRIMARY KEY (`id_bodytypes`),
              UNIQUE KEY `id_bodytypes` (`id_bodytypes`)
            ) ENGINE=MyISAM DEFAULT CHARSET=utf8
            """
        )
        log("  created table con_bodytypes")

    cur.execute("SHOW COLUMNS FROM con_sety LIKE 'bodytype'")
    if not cur.fetchone():
        cur.execute("ALTER TABLE con_sety ADD COLUMN `bodytype` int(11) DEFAULT NULL AFTER `wersja`")
        log("  added con_sety.bodytype")

    # Keep view in sync (trim + bodytype names for Versions UI).
    cur.execute(
        """
        CREATE OR REPLACE VIEW `con_sety_view` AS
        SELECT
          s.id_sety AS id_sety,
          s.model AS model,
          s.wersja AS wersja,
          s.bodytype AS bodytype,
          s.silnik AS silnik,
          s.rocznik AS rocznik,
          s.rmodel AS rmodel,
          s.promo AS promo,
          s.cena AS cena,
          s.arch AS arch,
          m.nazwa AS nazwa,
          w.wersja AS wer,
          bt.bodytype AS bt,
          x.silnik AS silnik_opis,
          x.fuel AS fuel,
          m.inactive AS inactive,
          w.lp AS wer_lp,
          bt.lp AS bt_lp
        FROM con_sety s
        LEFT JOIN con_modele m ON s.model = m.id_modele
        LEFT JOIN con_silniki x ON s.silnik = x.id_silniki
        LEFT JOIN con_wersje w ON s.wersja = w.id_wersje
        LEFT JOIN con_bodytypes bt ON s.bodytype = bt.id_bodytypes
        """
    )
    log("  refreshed con_sety_view (bodytype)")


def find_existing_model(cur: pymysql.cursors.Cursor) -> list[int]:
    cur.execute(
        """
        SELECT id_modele FROM con_modele
        WHERE code = %s OR website_model = %s OR kod = %s
        """,
        (MODEL_CODE, WEBSITE_MODEL, MODEL_CODE),
    )
    return [row[0] for row in cur.fetchall()]


def delete_model_data(cur: pymysql.cursors.Cursor, model_ids: list[int]) -> None:
    if not model_ids:
        return
    ph = ",".join(["%s"] * len(model_ids))
    cur.execute(f"SELECT id_opcje FROM con_opcje WHERE model IN ({ph})", model_ids)
    opcja_ids = [row[0] for row in cur.fetchall()]
    if opcja_ids:
        oph = ",".join(["%s"] * len(opcja_ids))
        cur.execute(f"DELETE FROM con_op2set WHERE opcja IN ({oph})", opcja_ids)
    for sql in (
        f"DELETE FROM con_wypos2set WHERE model IN ({ph})",
        f"DELETE FROM con_wyp2kat2mod WHERE model IN ({ph})",
        f"DELETE FROM con_sety WHERE model IN ({ph})",
        f"DELETE FROM con_opcje WHERE model IN ({ph})",
        f"DELETE FROM con_colors WHERE model IN ({ph})",
        f"DELETE FROM con_emisje WHERE model IN ({ph})",
        f"DELETE FROM con_footers WHERE model_id IN ({ph})",
        f"DELETE FROM con_modele WHERE id_modele IN ({ph})",
    ):
        cur.execute(sql, model_ids)
    log(f"  removed existing model ids={model_ids}")


def import_ducato(
    replace: bool = False,
    pdf_path: Path | None = DEFAULT_PDF,
    txt_path: Path | None = DEFAULT_TXT,
    options_path: Path | None = DEFAULT_OPTIONS,
) -> dict[str, Any]:
    log("Importing Ducato from Fiat CH PDF...")
    text = load_source_text(pdf_path, txt_path)
    rows = parse_price_rows(text)
    if not rows:
        raise RuntimeError("No Sincom price rows parsed from PDF/text")
    log(f"  parsed price rows = {len(rows)}")

    options_data = json.loads((options_path or DEFAULT_OPTIONS).read_text(encoding="utf-8"))

    conn = connect()
    cur = conn.cursor()
    try:
        ensure_bodytype_schema(cur)
        conn.commit()

        existing = find_existing_model(cur)
        if existing:
            if not replace:
                raise RuntimeError(
                    f"Ducato already exists (con_modele ids: {existing}). Re-run with --replace."
                )
            delete_model_data(cur, existing)
            conn.commit()

        model_id = max_id(cur, "con_modele", "id_modele") + 1
        next_wersja = max_id(cur, "con_wersje", "id_wersje") + 1
        next_bodytype = max_id(cur, "con_bodytypes", "id_bodytypes") + 1
        next_silnik = max_id(cur, "con_silniki", "id_silniki") + 1
        next_set = max_id(cur, "con_sety", "id_sety") + 1
        next_emisja = max_id(cur, "con_emisje", "id_emisje") + 1
        next_wypos = max_id(cur, "con_wypos", "id_con_wypos") + 1
        next_opcja = max_id(cur, "con_opcje", "id_opcje") + 1
        next_kat = max_id(cur, "con_kategorie", "id_kategorie") + 1
        next_wyp2kat = max_id(cur, "con_wyp2kat2mod", "id_wyp2kat2mod") + 1
        next_wypos2set = max_id(cur, "con_wypos2set", "id_con_wypos2set") + 1
        model_lp = max_id(cur, "con_modele", "lp") + 1

        cur.execute(
            """
            INSERT INTO con_modele (id_modele, kod, nazwa, lp, code, inactive, sf_code, website_model)
            VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
            """,
            (model_id, MODEL_CODE, MODEL_NAME, model_lp, MODEL_CODE, 0, None, WEBSITE_MODEL),
        )
        log(f"  inserted con_modele id={model_id}")

        # --- categories ---
        cur.execute("SELECT id_kategorie, nazwa FROM con_kategorie")
        existing_cats = {row[1]: row[0] for row in cur.fetchall()}
        category_map: dict[str, int] = {}
        for i, cat in enumerate(options_data.get("categories", []), start=1):
            name = cat["name_de"]
            if name in existing_cats:
                category_map[cat["code"]] = existing_cats[name]
            else:
                category_map[cat["code"]] = next_kat
                cur.execute(
                    """
                    INSERT INTO con_kategorie (id_kategorie, nazwa, kolejnosc, nazwa_fr, nazwa_it)
                    VALUES (%s, %s, %s, %s, %s)
                    """,
                    (
                        next_kat,
                        name,
                        i * 10,
                        cat.get("name_fr") or name,
                        cat.get("name_it") or name,
                    ),
                )
                existing_cats[name] = next_kat
                next_kat += 1

        # --- wersje = PDF trims (3 glass types only) ---
        TRIM_ORDER = (
            "Kastenwagen",
            "Kastenwagen teilverglast",
            "Kastenwagen vollverglast",
        )
        TRIM_CODES = {
            "Kastenwagen": "VERBL",
            "Kastenwagen teilverglast": "TVERGL",
            "Kastenwagen vollverglast": "VERGLA",
        }
        wersja_map: dict[str, int] = {}
        used_wersja_codes: set[str] = set()
        wersja_meta: dict[int, dict[str, Any]] = {}
        lp = 10
        needed = {row["wersja_name"] for row in rows}
        for name in TRIM_ORDER:
            if name not in needed:
                continue
            wid = next_wersja
            next_wersja += 1
            code = unique_code(TRIM_CODES[name], used_wersja_codes, 6)
            cur.execute(
                "INSERT INTO con_wersje (id_wersje, wersja, code, lp) VALUES (%s, %s, %s, %s)",
                (wid, clip(name, 64), code, lp),
            )
            wersja_map[name] = wid
            glass = {
                "Kastenwagen": "verblecht",
                "Kastenwagen teilverglast": "t-verglast",
                "Kastenwagen vollverglast": "verglast",
            }[name]
            wersja_meta[wid] = {"glass": glass, "name": name}
            lp += 10
        log(f"  inserted wersje (trims) = {len(wersja_map)}: {list(wersja_map)}")

        # --- bodytypes = LxHx [| Maxi] | tonnage (reuse existing by code/name) ---
        bodytype_map: dict[str, int] = {}
        used_bt_codes: set[str] = set()
        cur.execute("SELECT id_bodytypes, bodytype, code, lp FROM con_bodytypes")
        existing_bt_rows = cur.fetchall()
        existing_bts_by_code = {row[2]: row[0] for row in existing_bt_rows if row[2]}
        existing_bts_by_name = {row[1]: row[0] for row in existing_bt_rows if row[1]}
        used_bt_codes.update(existing_bts_by_code.keys())
        bt_lp = 10
        needed_bts = sorted(
            {(row["bodytype_name"], row["bodytype_code"]) for row in rows},
            key=lambda x: (
                x[0].split(" | ")[0],
                1 if "Maxi" in x[0] else 0,
                x[0],
            ),
        )
        reused_bt = 0
        for name, code_base in needed_bts:
            if code_base in existing_bts_by_code:
                bodytype_map[name] = int(existing_bts_by_code[code_base])
                reused_bt += 1
                continue
            if name in existing_bts_by_name:
                bodytype_map[name] = int(existing_bts_by_name[name])
                reused_bt += 1
                continue
            bid = next_bodytype
            next_bodytype += 1
            code = unique_code(code_base, used_bt_codes, 6)
            cur.execute(
                "INSERT INTO con_bodytypes (id_bodytypes, bodytype, code, lp) VALUES (%s, %s, %s, %s)",
                (bid, clip(name, 64), code, bt_lp),
            )
            bodytype_map[name] = bid
            existing_bts_by_code[code] = bid
            existing_bts_by_name[name] = bid
            bt_lp += 10
        log(
            f"  bodytypes = {len(bodytype_map)} "
            f"(reused {reused_bt}, inserted {len(bodytype_map) - reused_bt}): {list(bodytype_map)}"
        )

        # --- silniki ---
        engine_map: dict[str, int] = {}
        used_engine_codes: set[str] = set()
        for row in rows:
            key = row["engine_key"]
            if key in engine_map:
                continue
            sid = next_silnik
            next_silnik += 1
            code = unique_code(key, used_engine_codes, 16)
            cur.execute(
                """
                INSERT INTO con_silniki
                (id_silniki, silnik, ikona, code, displacement, fuel, powerKW, powerPS, torque, emissionClass)
                VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
                """,
                (
                    sid,
                    clip(row["engine_name"], 64),
                    None,
                    code,
                    row["displacement"],
                    row["fuel"],
                    row["power_kw"],
                    row["power_ps"],
                    "",
                    row["emission_class"],
                ),
            )
            engine_map[key] = sid
        log(f"  inserted silniki = {len(engine_map)}")

        # --- sety + emisje ---
        set_rows_meta: list[dict[str, Any]] = []
        emisja_seen: set[tuple[int, int, str]] = set()
        for row in rows:
            set_id = next_set
            next_set += 1
            wersja_id = wersja_map[row["wersja_name"]]
            bodytype_id = bodytype_map[row["bodytype_name"]]
            silnik_id = engine_map[row["engine_key"]]
            cur.execute(
                """
                INSERT INTO con_sety (id_sety, model, wersja, bodytype, silnik, rocznik, rmodel, promo, cena, arch)
                VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
                """,
                (
                    set_id,
                    model_id,
                    wersja_id,
                    bodytype_id,
                    silnik_id,
                    MODEL_YEAR,
                    MODEL_YEAR,
                    0,
                    row["price"],
                    0,
                ),
            )
            set_rows_meta.append(
                {
                    **row,
                    "set_id": set_id,
                    "wersja_id": wersja_id,
                    "bodytype_id": bodytype_id,
                    "silnik_id": silnik_id,
                }
            )

            emis_key = (silnik_id, row["gearbox"])
            if emis_key not in emisja_seen:
                emisja_seen.add(emis_key)
                # klasa is energy-efficiency letter (varchar(1)), not Euro class
                cur.execute(
                    """
                    INSERT INTO con_emisje
                    (id_emisje, model, silnik, skrzynia, naped, isg, klasa, co2, mieszany, miasto, trasa,
                     co2Max, mieszanyMax, miastoMax, trasaMax, mieszanyWh, miastoWh, co2treibstoff,
                     benzinequivalent, co2strombereitstellung)
                    VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
                    """,
                    (
                        next_emisja,
                        model_id,
                        silnik_id,
                        row["gearbox"],
                        "2WD",
                        "0",
                        None,
                        0 if row["is_bev"] else row["co2"],
                        None if row["is_bev"] else row["consumption"],
                        None,
                        None,
                        None,
                        None,
                        None,
                        None,
                        row["consumption"] if row["is_bev"] else None,
                        None,
                        None,
                        None,
                        None,
                    ),
                )
                next_emisja += 1
        log(f"  inserted sety = {len(set_rows_meta)}, emisje = {len(emisja_seen)}")

        # --- Serien- + Sonderausstattung → con_wypos / wypos2set (O/S/N), NOT con_opcje ---
        # Equipment UI: niedostępna=-1, opcja=0, standard=1
        equipment_items: list[dict[str, Any]] = []
        for item in options_data.get("serie", []):
            equipment_items.append({**item, "_source": "serie"})
        for item in options_data.get("options", []):
            equipment_items.append({**item, "_source": "sonder"})

        wypos_map: dict[str, int] = {}
        for i, item in enumerate(equipment_items):
            code = item["code"]
            if code in wypos_map:
                continue
            wid = next_wypos
            next_wypos += 1
            name = item["name_de"]
            label = f"{name} [{code}]" if item.get("_source") == "sonder" else name
            cur.execute(
                """
                INSERT INTO con_wypos (id_con_wypos, nazwa, kolejnosc, nazwa_fr, nazwa_it)
                VALUES (%s, %s, %s, %s, %s)
                """,
                (wid, clip(label, 256), (i + 1) * 10, clip(name, 256), clip(name, 256)),
            )
            wypos_map[code] = wid
            kat_code = item.get("category") or "KOMFORT"
            kat_id = category_map.get(kat_code) or category_map.get("SERIE")
            if kat_id:
                cur.execute(
                    """
                    INSERT INTO con_wyp2kat2mod (id_wyp2kat2mod, wypos, kategoria, model)
                    VALUES (%s, %s, %s, %s)
                    """,
                    (next_wyp2kat, wid, kat_id, model_id),
                )
                next_wyp2kat += 1

        wypos2set_rows: list[tuple[Any, ...]] = []
        for item in equipment_items:
            code = item["code"]
            wid = wypos_map[code]
            for wersja_id, meta in wersja_meta.items():
                relacja = equipment_relacja(item, meta["glass"], wersja_id, set_rows_meta)
                wypos2set_rows.append((next_wypos2set, wid, wersja_id, model_id, relacja))
                next_wypos2set += 1
        if wypos2set_rows:
            cur.executemany(
                """
                INSERT INTO con_wypos2set (id_con_wypos2set, wypos, wersja, model, relacja)
                VALUES (%s, %s, %s, %s, %s)
                """,
                wypos2set_rows,
            )
        log(
            f"  inserted wypos = {len(wypos_map)}, wypos2set = {len(wypos2set_rows)} "
            f"(Serien+Sonder -> Equipment O/S/N per trim)"
        )

        # Paid Options: only Sonderausstattung rows that are O (optional) somewhere + have price.
        # Equipment already holds full O/S/N; Options is the price/select matrix for O only.
        option_map: dict[str, int] = {}
        option_lp = 10
        paid_options = [
            opt
            for opt in options_data.get("options", [])
            if "price" in opt
            and any(
                availability_to_relacja(opt.get(k, "N")) == 0
                for k in ("verblecht", "t_verglast", "verglast")
            )
        ]
        for opt in paid_options:
            oid = next_opcja
            next_opcja += 1
            name = opt["name_de"]
            kat = category_map.get(opt.get("category") or "FUNKTION")
            cur.execute(
                """
                INSERT INTO con_opcje
                (id_opcje, model, grupa, nazwa, nazwa_fr, nazwa_it, pn, cena, opis, opis_fr, opis_it,
                 obraz, lp, wymaga, wyklucza, hidden, kodemisji, kategoria)
                VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
                """,
                (
                    oid,
                    model_id,
                    None,
                    clip(name, 128),
                    clip(name, 128),
                    clip(name, 128),
                    clip(opt["code"], 32),
                    Decimal(str(opt.get("price") or 0)),
                    None,
                    None,
                    None,
                    None,
                    option_lp,
                    None,
                    None,
                    0,
                    None,
                    kat,
                ),
            )
            option_map[opt["code"]] = oid
            option_lp += 10

        # op2set: Options grid columns = id_sety (not id_wersje).
        # Presence = available; relacja=-1 = paid option; relacja=1 = standard.
        op2set_rows: list[tuple[Any, ...]] = []
        for opt in paid_options:
            oid = option_map[opt["code"]]
            price = Decimal(str(opt.get("price") or 0))
            fuel = opt.get("fuel", "all")
            for srow in set_rows_meta:
                if fuel == "bev" and not srow["is_bev"]:
                    continue
                if fuel == "ice" and srow["is_bev"]:
                    continue
                flag_key = GLASS_FLAG_KEY[srow["glass"]]
                if availability_to_relacja(opt.get(flag_key, "O")) != 0:
                    continue
                op2set_rows.append((oid, srow["set_id"], -1, price))
        if op2set_rows:
            for start in range(0, len(op2set_rows), 5000):
                cur.executemany(
                    "INSERT INTO con_op2set (opcja, setx, relacja, cena) VALUES (%s, %s, %s, %s)",
                    op2set_rows[start : start + 5000],
                )
        log(
            f"  inserted opcje = {len(option_map)} (O+price only), "
            f"op2set = {len(op2set_rows)} (per set where O)"
        )

        footer_id = max_id(cur, "con_footers", "id") + 1
        cur.execute(
            """
            INSERT INTO con_footers (id, model_id, silnik_id, text_de, text_fr, text_it)
            VALUES (%s, %s, %s, %s, %s, %s)
            """,
            (footer_id, model_id, None, FOOTER_DE, FOOTER_DE, FOOTER_DE),
        )

        conn.commit()
        bev_sample = next((r for r in set_rows_meta if r["sincom"] == "505.BG1.2"), None)
        stats = {
            "model_id": model_id,
            "wersje": len(wersja_map),
            "bodytypes": len(bodytype_map),
            "silniki": len(engine_map),
            "sety": len(set_rows_meta),
            "emisje": len(emisja_seen),
            "wypos": len(wypos_map),
            "wypos2set": len(wypos2set_rows),
            "opcje": len(option_map),
            "op2set": len(op2set_rows),
            "bev_505_BG1_2": (
                {
                    "wersja": bev_sample["wersja_name"],
                    "bodytype": bev_sample["bodytype_name"],
                    "cena": str(bev_sample["price"]),
                    "silnik": bev_sample["engine_name"],
                }
                if bev_sample
                else None
            ),
        }
        print("Import Ducato completed:", stats)
        return stats
    except Exception:
        conn.rollback()
        raise
    finally:
        conn.close()


def main() -> None:
    args = sys.argv[1:]
    replace = "--replace" in args
    args = [a for a in args if a != "--replace"]
    pdf = Path(args[0]) if args else DEFAULT_PDF
    txt = DEFAULT_TXT if DEFAULT_TXT.exists() else None
    if not pdf.exists() and txt is None:
        raise SystemExit(f"Missing PDF {pdf} and text cache {DEFAULT_TXT}")
    import_ducato(replace=replace, pdf_path=pdf if pdf.exists() else None, txt_path=txt)


if __name__ == "__main__":
    main()
