#!/usr/bin/env python3
"""Remove duplicate Tucson imports from astara_pdb_demo_hy and fix broken FKs."""
from __future__ import annotations

import pymysql

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

KEEP_MODEL_ID = 25
DROP_MODEL_IDS = (23, 24)

# After manual silnik dedup: old set refs -> surviving silnik ids.
SILNIK_REMAP = {
    38: 24,
    39: 25,
    40: 26,
    41: 27,
    42: 28,
    43: 29,
    44: 30,
}


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


def delete_model(cur: pymysql.cursors.Cursor, model_id: int) -> None:
    cur.execute("SELECT id_sety FROM con_sety WHERE model = %s", (model_id,))
    set_ids = [row[0] for row in cur.fetchall()]
    if set_ids:
        placeholders = ",".join(["%s"] * len(set_ids))
        cur.execute(f"DELETE FROM con_op2set WHERE setx IN ({placeholders})", set_ids)

    cur.execute("DELETE FROM con_wypos2set WHERE model = %s", (model_id,))
    cur.execute("DELETE FROM con_wyp2kat2mod WHERE model = %s", (model_id,))
    cur.execute("DELETE FROM con_sety WHERE model = %s", (model_id,))
    cur.execute("DELETE FROM con_colors WHERE model = %s", (model_id,))

    cur.execute("SELECT id_opcje FROM con_opcje WHERE model = %s", (model_id,))
    option_ids = [row[0] for row in cur.fetchall()]
    if option_ids:
        placeholders = ",".join(["%s"] * len(option_ids))
        cur.execute(f"DELETE FROM con_op2set WHERE opcja IN ({placeholders})", option_ids)
    cur.execute("DELETE FROM con_opcje WHERE model = %s", (model_id,))

    cur.execute("DELETE FROM con_emisje WHERE model = %s", (model_id,))
    cur.execute("DELETE FROM con_footers WHERE model_id = %s", (model_id,))
    cur.execute("DELETE FROM con_ak2mod WHERE model = %s", (model_id,))
    cur.execute("DELETE FROM con_modele WHERE id_modele = %s", (model_id,))


def remap_silniki(cur: pymysql.cursors.Cursor, model_id: int) -> int:
    updated = 0
    for old_id, new_id in SILNIK_REMAP.items():
        cur.execute(
            "UPDATE con_sety SET silnik = %s WHERE model = %s AND silnik = %s",
            (new_id, model_id, old_id),
        )
        updated += cur.rowcount
        cur.execute(
            "UPDATE con_emisje SET silnik = %s WHERE model = %s AND silnik = %s",
            (new_id, model_id, old_id),
        )
        updated += cur.rowcount
        cur.execute(
            "UPDATE con_footers SET silnik_id = %s WHERE model_id = %s AND silnik_id = %s",
            (new_id, model_id, old_id),
        )
        updated += cur.rowcount
    return updated


def delete_orphan_wersje(cur: pymysql.cursors.Cursor) -> int:
    cur.execute(
        """
        DELETE w FROM con_wersje w
        LEFT JOIN con_sety s ON s.wersja = w.id_wersje
        WHERE s.id_sety IS NULL
          AND w.id_wersje >= 21
        """
    )
    return cur.rowcount


def delete_orphan_wypos(cur: pymysql.cursors.Cursor, keep_model_id: int) -> int:
    cur.execute(
        """
        DELETE w FROM con_wypos w
        LEFT JOIN con_wypos2set ws ON ws.wypos = w.id_con_wypos
        LEFT JOIN con_wyp2kat2mod wk ON wk.wypos = w.id_con_wypos
        WHERE ws.id_con_wypos2set IS NULL
          AND wk.id_wyp2kat2mod IS NULL
          AND w.id_con_wypos >= 978
        """
    )
    return cur.rowcount


def main() -> None:
    conn = connect()
    cur = conn.cursor()
    try:
        for model_id in DROP_MODEL_IDS:
            delete_model(cur, model_id)
            print(f"deleted model {model_id}")

        remapped = remap_silniki(cur, KEEP_MODEL_ID)
        print(f"remapped silnik refs on model {KEEP_MODEL_ID}: {remapped}")

        orphan_wersje = delete_orphan_wersje(cur)
        print(f"deleted orphan wersje: {orphan_wersje}")

        orphan_wypos = delete_orphan_wypos(cur, KEEP_MODEL_ID)
        print(f"deleted orphan wypos: {orphan_wypos}")

        cur.execute(
            """
            SELECT COUNT(*) FROM con_sety s
            LEFT JOIN con_silniki si ON si.id_silniki = s.silnik
            WHERE s.model = %s AND si.id_silniki IS NULL
            """,
            (KEEP_MODEL_ID,),
        )
        broken_sets = cur.fetchone()[0]
        if broken_sets:
            raise RuntimeError(f"model {KEEP_MODEL_ID} still has {broken_sets} sets with missing silnik")

        conn.commit()

        cur.execute("SELECT COUNT(*) FROM con_modele WHERE code = 'TUC'")
        print("tucson models left:", cur.fetchone()[0])
        cur.execute("SELECT COUNT(*) FROM con_sety WHERE model = %s", (KEEP_MODEL_ID,))
        print("tucson sets left:", cur.fetchone()[0])
        cur.execute("SELECT rocznik, COUNT(*) FROM con_sety WHERE model = %s GROUP BY rocznik", (KEEP_MODEL_ID,))
        print("by year:", cur.fetchall())
    except Exception:
        conn.rollback()
        raise
    finally:
        conn.close()


if __name__ == "__main__":
    main()
