#!/usr/bin/env python3
import json
import sqlite3
import os
import secrets
from datetime import datetime

DB_PATH = 'pb_data/data.db'
DUMP_DIR = 'starbase_dumps'

def generate_pb_id():
    chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
    return ''.join(secrets.choice(chars) for _ in range(15))

def clean(val):
    if not val:
        return ''
    return str(val).strip()

def detect_category(contact_str, last_name_str):
    combined = f"{contact_str} {last_name_str}".lower()
    if '10 vstup' in combined:
        return 'Balíček 10 vstupů', 10
    if '6 vstup' in combined:
        return 'Balíček 6 vstupů', 6
    if 'vip' in combined:
        return 'VIP', 999
    if 'mecenáš' in combined or 'mecenas' in combined:
        return 'Mecenáš', 999
    if 'press' in combined or 'novinář' in combined:
        return 'Press', 999
    if 'štáb' in combined or 'stab' in combined:
        return 'Štáb', 999
    if 'víkend' in combined or 'vikend' in combined:
        return 'Víkendová', 999
    if 'jednodenní' in combined or '1 den' in combined:
        return 'Jednodenní', 999
    return 'Celotýdenní', 999

def migrate():
    con = sqlite3.connect(DB_PATH)
    cur = con.cursor()

    years = [2024, 2025, 2026]
    now = datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.000Z')

    total_accs_migrated = 0
    total_guests_migrated = 0

    for yr in years:
        acc_file = os.path.join(DUMP_DIR, f'accreditations_{yr}.json')
        guest_file = os.path.join(DUMP_DIR, f'guests_{yr}.json')

        # 1. GUESTS
        if os.path.exists(guest_file):
            with open(guest_file, 'r', encoding='utf-8') as f:
                guests_data = json.load(f)

            print(f"\nMigrating {len(guests_data)} guests for year {yr}...")
            # Check existing guests for this year to avoid duplicates
            existing_guests = set(
                row[0] for row in cur.execute("SELECT full_name FROM guests WHERE festival_year = ?", (yr,)).fetchall()
            )

            inserted_guests = 0
            for g in guests_data:
                name = clean(g.get('CONTACT') or f"{g.get('FIRST_NAME', '')} {g.get('LAST_NAME', '')}")
                if not name or name in existing_guests:
                    continue

                gid = generate_pb_id()
                country = clean(g.get('COUNTRY')) or 'CZ'
                email = clean(g.get('EMAIL'))
                phone = ''
                hotel_name = 'Hotel Grand' if yr == 2026 else 'Hotel StarBase (Archiv)'
                room_number = ''
                notes = 'Host z evidence StarBase'
                stay_from = g.get('stay_from') or ''
                stay_to = g.get('stay_to') or ''
                partner_name = ''
                category = 'VIP_A'
                inv_status = 'CONFIRMED'

                cur.execute("""
                    INSERT INTO guests (
                        id, full_name, category, country, email, phone,
                        invitation_status, hotel_name, room_number, accommodation_notes,
                        stay_from, stay_to, partner_name, has_opening_ticket,
                        has_closing_ticket, has_reception_ticket, festival_year,
                        created, updated
                    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, 1, 1, ?, ?, ?)
                """, (
                    gid, name, category, country, email, phone,
                    inv_status, hotel_name, room_number, notes,
                    stay_from, stay_to, partner_name, yr,
                    now, now
                ))
                existing_guests.add(name)
                inserted_guests += 1

            total_guests_migrated += inserted_guests
            print(f"  ✓ Inserted {inserted_guests} new guests for year {yr}")

        # 2. ACCREDITATIONS
        if os.path.exists(acc_file):
            with open(acc_file, 'r', encoding='utf-8') as f:
                accs_data = json.load(f)

            print(f"Migrating {len(accs_data)} accreditations for year {yr}...")
            # Get existing qr codes
            existing_qrs = set(
                row[0] for row in cur.execute("SELECT qr_code FROM accreditations WHERE festival_year = ?", (yr,)).fetchall()
            )

            inserted_accs = 0
            for a in accs_data:
                id_person = a.get('ID_PERSON') or a.get('UID')
                qr_code = f"LFS{str(yr)[2:]}-ACC-{id_person}"
                if qr_code in existing_qrs:
                    continue

                holder_name = clean(a.get('CONTACT') or f"{a.get('FIRST_NAME', '')} {a.get('LAST_NAME', '')}")
                if not holder_name:
                    continue

                email = clean(a.get('EMAIL')) or f"akreditace_{id_person}@lfs.cz"
                category, admissions = detect_category(a.get('CONTACT', ''), a.get('LAST_NAME', ''))
                
                aid = generate_pb_id()
                amount_czk = 2600 if category == 'Celotýdenní' else (1300 if 'Balíček' in category else 0)

                cur.execute("""
                    INSERT INTO accreditations (
                        id, qr_code, holder_name, holder_email, holder_phone,
                        category, guest_id, payment_status, payment_method,
                        receipt_number, is_issued, issued_at, festival_year,
                        admissions_total, admissions_remaining, amount_czk,
                        order_number, has_opening_ticket, has_closing_ticket,
                        has_reception_ticket, created, updated
                    ) VALUES (?, ?, ?, ?, '', ?, '', 'Zaplaceno', 'Hrazeno', '', 1, ?, ?, ?, ?, ?, '', 0, 0, 0, ?, ?)
                """, (
                    aid, qr_code, holder_name, email,
                    category, now, yr,
                    admissions, admissions, amount_czk,
                    now, now
                ))
                existing_qrs.add(qr_code)
                inserted_accs += 1

            total_accs_migrated += inserted_accs
            print(f"  ✓ Inserted {inserted_accs} new accreditations for year {yr}")

    con.commit()
    con.close()

    print(f"\n🎉 Migration finished!")
    print(f"Total guests inserted: {total_guests_migrated}")
    print(f"Total accreditations inserted: {total_accs_migrated}")

if __name__ == '__main__':
    migrate()
