from __future__ import annotations

"""Seed official Thông tư 38/2026/TT-BXD norm rules and correct any existing Larsen items."""

from app.core.postgres.erp_client import ErpDatabaseClient


def seed_thong_tu_38():
    client = ErpDatabaseClient()
    conn = client.get_connection()
    with conn.cursor() as cur:
        # Update existing items
        cur.execute(
            """
            UPDATE erp_drawing_takeoff_items
            SET norm_code = 'AC.22111'
            WHERE (LOWER(item_name) LIKE %s OR LOWER(item_name) LIKE %s)
              AND (norm_code = 'AC.11110' OR norm_code = 'AC.12110' OR norm_code = 'AC.11120')
              AND LOWER(item_name) NOT LIKE %s;
        """,
            ("%larsen%", "%cừ thép%", "%nhổ%"),
        )
        updated_ep = cur.rowcount

        cur.execute(
            """
            UPDATE erp_drawing_takeoff_items
            SET norm_code = 'AC.22112'
            WHERE (LOWER(item_name) LIKE %s OR LOWER(item_name) LIKE %s)
              AND (LOWER(item_name) LIKE %s OR LOWER(item_name) LIKE %s);
        """,
            ("%larsen%", "%cừ thép%", "%nhổ%", "%nho%"),
        )
        updated_nho = cur.rowcount

        # Upsert rule
        rule_error = (
            "Nhầm lẫn mã định mức AC.11110 (cọc tre) cho công tác cọc cừ thép Larsen IV"
        )
        rule_corr = "TUÂN THỦ THÔNG TƯ 38/2026/TT-BXD: Công tác ép cọc cừ thép Larsen IV bắt buộc áp mã AC.22111 (trên cạn) hoặc AC.22121 (dưới nước). Công tác nhổ cọc cừ thép Larsen IV áp mã AC.22112 (trên cạn) hoặc AC.22122 (dưới nước). Tuyệt đối không dùng AC.11110 (đây là định mức đóng cọc tre). Đơn vị tính: md hoặc 100m cừ hoặc tấn."

        cur.execute(
            """
            SELECT id FROM erp_ai_takeoff_learned_rules
            WHERE error_pattern = %s OR correction_rule LIKE %s;
        """,
            (rule_error, "%THÔNG TƯ 38/2026/TT-BXD%"),
        )
        row = cur.fetchone()

        if row:
            cur.execute(
                """
                UPDATE erp_ai_takeoff_learned_rules
                SET error_pattern = %s,
                    correction_rule = %s,
                    confidence_weight = 1.0,
                    apply_count = apply_count + 10,
                    is_active = TRUE,
                    updated_at = NOW()
                WHERE id = %s;
            """,
                (rule_error, rule_corr, row["id"]),
            )
            print(f"Updated existing rule id={row['id']}")
        else:
            cur.execute(
                """
                INSERT INTO erp_ai_takeoff_learned_rules (
                    drawing_type, category, error_pattern, correction_rule, learned_from_user, confidence_weight, apply_count, is_active
                ) VALUES (
                    'general', 'foundation', %s, %s, 'Ban Giám Đốc / Kỹ Sư Trưởng QS', 1.0, 50, TRUE
                );
            """,
                (rule_error, rule_corr),
            )
            print("Inserted new Thông tư 38 rule")

        conn.commit()
        print(f"Items corrected: Ep={updated_ep}, Nho={updated_nho}")
    conn.close()


if __name__ == "__main__":
    seed_thong_tu_38()
