#!/usr/bin/env python3
import sqlite3
import shutil
import time
import re
import unicodedata
from datetime import datetime

DB_PATH = 'pb_data/data.db'

FESTIVAL_DATES = {
    2017: ("2017-07-28 00:00:00.000Z", "2017-08-06 23:59:59.000Z"),
    2018: ("2018-07-27 00:00:00.000Z", "2018-08-05 23:59:59.000Z"),
    2019: ("2019-07-26 00:00:00.000Z", "2019-08-04 23:59:59.000Z"),
    2020: ("2020-08-07 00:00:00.000Z", "2020-08-12 23:59:59.000Z"),
    2021: ("2021-08-06 00:00:00.000Z", "2021-08-12 23:59:59.000Z"),
    2022: ("2022-07-29 00:00:00.000Z", "2022-08-04 23:59:59.000Z"),
    2023: ("2023-07-28 00:00:00.000Z", "2023-08-03 23:59:59.000Z"),
    2024: ("2024-07-26 00:00:00.000Z", "2024-08-01 23:59:59.000Z"),
    2025: ("2025-07-25 00:00:00.000Z", "2025-07-31 23:59:59.000Z"),
    2026: ("2026-07-24 00:00:00.000Z", "2026-07-30 23:59:59.000Z"),
}

def normalize_name(s):
    if not s:
        return ""
    s = s.strip().lower()
    # Remove accents for resilient matching
    nfkd = unicodedata.normalize('NFKD', s)
    return "".join(c for c in nfkd if not unicodedata.combining(c))

def map_guest_category(cat):
    if not cat:
        return 'VIP'
    cat = cat.upper()
    if 'PRESS' in cat:
        return 'Press'
    if 'MECENAS' in cat:
        return 'Mecenáš'
    if 'DELEGACE' in cat:
        return 'Host'
    return 'VIP'

def run_fix():
    print("🎬 Starting fix of historical accreditations...")
    backup_file = f"pb_data/data.db.backup_acc_fix_{int(time.time())}"
    shutil.copy2(DB_PATH, backup_file)
    print(f"📦 Backup created at: {backup_file}")

    con = sqlite3.connect(DB_PATH)
    cur = con.cursor()

    # 1. Load guests into fast lookup maps
    cur.execute("""
        SELECT id, full_name, category, stay_from, stay_to,
               has_opening_ticket, has_closing_ticket, has_reception_ticket,
               festival_year, email
        FROM guests
    """)
    guests_by_name = {}
    guests_by_email = {}

    guest_count = 0
    for row in cur.fetchall():
        gid, name, cat, s_from, s_to, hop, hcl, hrc, yr, email = row
        norm_name = normalize_name(name)
        g_data = {
            'id': gid,
            'name': name,
            'category': cat,
            'stay_from': s_from or '',
            'stay_to': s_to or '',
            'has_opening': hop or 0,
            'has_closing': hcl or 0,
            'has_reception': hrc or 0,
            'year': yr
        }
        if yr not in guests_by_name:
            guests_by_name[yr] = {}
            guests_by_email[yr] = {}
        guests_by_name[yr][norm_name] = g_data
        if email and email.strip() and not email.endswith('@lfs.cz'):
            guests_by_email[yr][email.strip().lower()] = g_data
        guest_count += 1

    print(f"👥 Loaded {guest_count} guests for cross-referencing.")

    # 2. Fetch all accreditations
    cur.execute("""
        SELECT id, holder_name, holder_email, festival_year
        FROM accreditations
    """)
    all_accs = cur.fetchall()
    total_accs = len(all_accs)
    print(f"🎫 Total accreditations to process: {total_accs}")

    now_iso = datetime.now().strftime('%Y-%m-%d %H:%M:%S.000Z')

    updated_guests = 0
    updated_packages = 0
    updated_singleday = 0
    updated_general = 0

    batch = []

    for acc_id, holder_name, email, yr in all_accs:
        yr = int(yr or 2026)
        fest_start, fest_end = FESTIVAL_DATES.get(yr, FESTIVAL_DATES[2026])

        norm_name = normalize_name(holder_name)
        clean_email = (email or '').strip().lower()

        # Check if matched with guest
        matched_guest = None
        if yr in guests_by_name and norm_name in guests_by_name[yr]:
            matched_guest = guests_by_name[yr][norm_name]
        elif yr in guests_by_email and clean_email in guests_by_email[yr]:
            matched_guest = guests_by_email[yr][clean_email]

        if matched_guest:
            # GUEST ACCREDITATION
            cat = map_guest_category(matched_guest['category'])
            v_from = matched_guest['stay_from'] if (matched_guest['stay_from'] and str(yr) in matched_guest['stay_from']) else fest_start
            v_to = matched_guest['stay_to'] if (matched_guest['stay_to'] and str(yr) in matched_guest['stay_to']) else fest_end
            
            batch.append((
                cat, matched_guest['id'], 'Zaplaceno', 'Hrazeno',
                v_from, v_to, 999, 999, 0,
                matched_guest['has_opening'], matched_guest['has_closing'], matched_guest['has_reception'],
                now_iso, acc_id
            ))
            updated_guests += 1
            continue

        # Check special ticket packages
        lower_name = (holder_name or '').lower()
        
        # 10 vstupů
        if re.search(r'10\s*vstup', lower_name):
            batch.append((
                'Balíček 10 vstupů', '', 'Zaplaceno', 'Hrazeno',
                fest_start, fest_end, 10, 10, 2000,
                0, 0, 0, now_iso, acc_id
            ))
            updated_packages += 1
            continue

        # 6 vstupů / 8 vstupů / 12 vstupů
        if re.search(r'6\s*vstup|12\s*vstup|8\s*vstup|4\s*vstup', lower_name):
            adm = 6
            if '12 vstup' in lower_name: adm = 12
            elif '8 vstup' in lower_name: adm = 8
            elif '4 vstup' in lower_name: adm = 4
            batch.append((
                'Balíček 6 vstupů', '', 'Zaplaceno', 'Hrazeno',
                fest_start, fest_end, adm, adm, 1300,
                0, 0, 0, now_iso, acc_id
            ))
            updated_packages += 1
            continue

        # Jednodenní volná s konkrétním datem (např. Jednodenní volná 2018-07-27)
        date_match = re.search(r'(\d{4}-\d{2}-\d{2})', lower_name)
        if 'jednodenn' in lower_name and date_match:
            d_str = date_match.group(1)
            v_from = f"{d_str} 00:00:00.000Z"
            v_to = f"{d_str} 23:59:59.000Z"
            batch.append((
                'Jednodenní', '', 'Zaplaceno', 'Hrazeno',
                v_from, v_to, 1, 1, 450,
                0, 0, 0, now_iso, acc_id
            ))
            updated_singleday += 1
            continue

        if 'jednodenn' in lower_name:
            batch.append((
                'Jednodenní', '', 'Zaplaceno', 'Hrazeno',
                fest_start, fest_end, 1, 1, 450,
                0, 0, 0, now_iso, acc_id
            ))
            updated_singleday += 1
            continue

        # Regular attendee: Celotýdenní with exact festival dates
        batch.append((
            'Celotýdenní', '', 'Zaplaceno', 'Hrazeno',
            fest_start, fest_end, 999, 999, 2600,
            0, 0, 0, now_iso, acc_id
        ))
        updated_general += 1

    print("💾 Executing batch update in SQLite...")
    cur.executemany("""
        UPDATE accreditations
        SET category = ?,
            guest_id = ?,
            payment_status = ?,
            payment_method = ?,
            valid_from = ?,
            valid_to = ?,
            admissions_total = ?,
            admissions_remaining = ?,
            amount_czk = ?,
            has_opening_ticket = ?,
            has_closing_ticket = ?,
            has_reception_ticket = ?,
            updated = ?
        WHERE id = ?
    """, batch)

    con.commit()
    con.close()

    print("\n✅ Repair finished successfully!")
    print(f"  🌟 VIP & Guest accreditations linked: {updated_guests}")
    print(f"  🎟️ Ticket packages (6/10 vstupů):     {updated_packages}")
    print(f"  📅 Single day accreditations:          {updated_singleday}")
    print(f"  🎫 Standard Celotýdenní accreditations:{updated_general}")
    print(f"  --------------------------------------------------")
    print(f"  Total accreditations updated:          {len(batch)}")

if __name__ == '__main__':
    run_fix()
