#!/usr/bin/env python3
import os
import shutil
import sqlite3
import random
import string
import zipfile
import json
import xml.etree.ElementTree as ET
from datetime import datetime, timezone, timedelta

def gen_id():
    chars = string.ascii_lowercase + string.digits
    return ''.join(random.choice(chars) for _ in range(15))

def now_iso():
    return datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M:%S.000Z')

def extract_excel(file_path):
    with zipfile.ZipFile(file_path) as z:
        shared_strings = []
        if 'xl/sharedStrings.xml' in z.namelist():
            ss_root = ET.fromstring(z.read('xl/sharedStrings.xml'))
            for si in ss_root.findall('{http://schemas.openxmlformats.org/spreadsheetml/2006/main}si'):
                text = ''.join(t.text for t in si.iter('{http://schemas.openxmlformats.org/spreadsheetml/2006/main}t') if t.text)
                shared_strings.append(text)
        sheet_root = ET.fromstring(z.read('xl/worksheets/sheet1.xml'))
        rows = sheet_root.findall('{http://schemas.openxmlformats.org/spreadsheetml/2006/main}sheetData/{http://schemas.openxmlformats.org/spreadsheetml/2006/main}row')
        
        header = []
        for c in rows[0].findall('{http://schemas.openxmlformats.org/spreadsheetml/2006/main}c'):
            t = c.attrib.get('t')
            v = c.find('{http://schemas.openxmlformats.org/spreadsheetml/2006/main}v')
            val = v.text if v is not None else ''
            if t == 's' and val != '': val = shared_strings[int(val)]
            header.append(val)
            
        items = []
        for r in rows[1:]:
            vals = []
            for c in r.findall('{http://schemas.openxmlformats.org/spreadsheetml/2006/main}c'):
                t = c.attrib.get('t')
                v = c.find('{http://schemas.openxmlformats.org/spreadsheetml/2006/main}v')
                val = v.text if v is not None else ''
                if t == 's' and val != '': val = shared_strings[int(val)]
                vals.append(val)
            item = {}
            for h, v in zip(header, vals):
                item[h] = v
            items.append(item)
        return items

def parse_date_czech(d_str, t_str):
    if not d_str: return None
    time_part = t_str.strip() if t_str else '12:00'
    try:
        hour, minute = [int(x) for x in time_part.split(':')[:2]]
    except:
        hour, minute = 12, 0

    if '.' in d_str:
        parts = [int(p) for p in d_str.strip().split('.') if p]
        if len(parts) == 3:
            day, mon, year = parts
            return datetime(year, mon, day, hour, minute, tzinfo=timezone.utc)
    return None

def main():
    db_path = 'pb_data/data.db'
    backup_path = 'pb_data/data.db.backup'
    print(f"📦 Zálohuji databázi: {db_path} -> {backup_path}")
    shutil.copy2(db_path, backup_path)

    print("📖 Načítám soubory z podkladů...")
    raw_zdroj = extract_excel('podklady/zdrojovy.xlsx')
    print(f"  Zdrojová brožura (anotace & data): {len(raw_zdroj)} řádků")
    raw_tech = extract_excel('podklady/technicky-scenar-2026-07-15-verze-0.xlsx')
    print(f"  Technický scénář (kapacity & formáty): {len(raw_tech)} řádků")

    # Map venue capacities from tech
    venue_cap_map = {}
    for t in raw_tech:
        v = t.get('Venue', '').strip()
        if v and v not in venue_cap_map:
            cap = int(t.get('Capacity', '200') or 200)
            in_h = int(t.get('In-house', '0') or 0)
            if in_h == 0: in_h = max(10, int(cap * 0.1))
            venue_cap_map[v] = (cap, in_h)

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

    print("🧹 Čistím staré záznamy...")
    cur.execute("DELETE FROM entry_logs")
    cur.execute("DELETE FROM accreditations")
    cur.execute("DELETE FROM screenings")
    cur.execute("DELETE FROM movies")
    cur.execute("DELETE FROM venues")
    cur.execute("DELETE FROM guests")
    cur.execute("DELETE FROM bulletin")

    now = now_iso()

    # 1. VENUES
    print("\n🏛️ Vkládám festivalové sály (venues)...")
    venue_id_map = {}
    
    # Collect all unique venues from zdrojovy
    unique_venues = sorted(list(set(r.get('Kino', '').strip() for r in raw_zdroj if r.get('Kino'))))
    for v_name in unique_venues:
        cap, in_h = venue_cap_map.get(v_name, (200, 20))
        code = v_name[:3].upper()
        if 'Hvězda' in v_name: code = 'HVZ'
        elif 'Slovácké divadlo' in v_name: code = 'SD'
        elif 'Reduta - Velký' in v_name: code = 'RED-VS'
        elif 'Reduta - Komorní' in v_name: code = 'RED-KS'
        elif 'Reduta' in v_name: code = 'RED'
        elif 'Mír' in v_name: code = 'MIR'
        elif 'Smetanovy' in v_name: code = 'LET-SMET'
        elif 'Sportovní hala' in v_name: code = 'HALA'
        elif 'Stan ČRo' in v_name or 'Rozhlas' in v_name: code = 'STAN-CRO'
        elif 'Stan ČT' in v_name: code = 'STAN-CT'
        elif 'Amfiteátr' in v_name: code = 'ROCHUS'

        v_id = gen_id()
        cur.execute("""
            INSERT INTO venues (id, created, updated, name, code, capacity_total, capacity_in_house, is_active)
            VALUES (?, ?, ?, ?, ?, ?, ?, 1)
        """, (v_id, now, now, v_name, code, cap, in_h))
        venue_id_map[v_name] = v_id

    print(f"  ✅ Vloženo {len(venue_id_map)} unikátních sálů.")

    # 2. MOVIES 2026
    print("\n🎬 Vkládám festivalový katalog 2026 (movies)...")
    movie_id_map = {}
    movies_count = 0

    for row in raw_zdroj:
        title_cz = row.get('Český název', '').strip()
        if not title_cz or title_cz in movie_id_map:
            continue

        title_en = row.get('Anglický název', '').strip() or title_cz
        director = row.get('Režie', '').strip()
        year = int(row.get('Rok', '2026') or 2026)
        duration = int(row.get('Délka', '90') or 90)
        section = row.get('Sekce', '').strip() or 'Hlavní program'
        synopsis = row.get('Synopse', '').strip() or f"Oficiální festivalová projekce LFŠ 2026 v sekci {section}."

        m_id = gen_id()
        cur.execute("""
            INSERT INTO movies (id, created, updated, title_cz, title_en, director, year, duration_minutes, section, synopsis, photo, status, is_published, festival_year)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, '', 'Confirmed', 1, 2026)
        """, (m_id, now, now, title_cz, title_en, director, year, duration, section, synopsis))
        movie_id_map[title_cz] = (m_id, duration)
        movies_count += 1

    print(f"  ✅ Vloženo {movies_count} filmů pro LFŠ 2026 s plnými anotacemi.")

    # 3. SCREENINGS 2026
    print("\n🎟️ Vkládám harmonogram projekcí 2026 s reálnými daty (screenings)...")
    screenings_count = 0

    for row in raw_zdroj:
        title_cz = row.get('Český název', '').strip()
        v_name = row.get('Kino', '').strip()
        d_val = row.get('Datum', '').strip()
        t_val = row.get('Čas', '').strip()

        if not title_cz or title_cz not in movie_id_map or not v_name or v_name not in venue_id_map:
            continue

        start_dt = parse_date_czech(d_val, t_val)
        if not start_dt:
            continue

        m_id, duration = movie_id_map[title_cz]
        v_id = venue_id_map[v_name]

        end_dt = start_dt + timedelta(minutes=duration)
        start_iso = start_dt.strftime('%Y-%m-%d %H:%M:%S.000Z')
        end_iso = end_dt.strftime('%Y-%m-%d %H:%M:%S.000Z')

        raw_fmt = (row.get('Formát', '') or 'DCP').upper()
        copy_fmt = 'DCP'
        if '35' in raw_fmt: copy_fmt = '35mm'
        elif '16' in raw_fmt: copy_fmt = '16mm'
        elif 'DATA' in raw_fmt or 'PRORES' in raw_fmt: copy_fmt = 'Data'

        s_id = gen_id()
        cur.execute("""
            INSERT INTO screenings (id, created, updated, movie_id, venue_id, start_time, end_time, copy_format, status, in_house_released, festival_year)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'Plánováno', 0, 2026)
        """, (s_id, now, now, m_id, v_id, start_iso, end_iso, copy_fmt))
        screenings_count += 1

    print(f"  ✅ Vloženo {screenings_count} časových projekcí se skutečnými festivalovými daty.")

    # 4. HISTORICKÉ EDICE 2024 a 2025 (pro archiv)
    def import_hist(fpath, y):
        if not os.path.exists(fpath): return 0
        with open(fpath, 'r', encoding='utf-8') as f:
            films = json.load(f)
        c = 0
        for film in films:
            title = film.get('TITLE') or film.get('TITLE_LOCAL') or 'Bez názvu'
            title_en = film.get('TITLE_ENGLISH') or title
            dur = int(film.get('RUNTIME', 0) or 90)
            py = int(film.get('PRODUCTION_YEAR', 0) or y)
            sec = f"LFŠ {y}"
            syn = f"Uvedeno v oficiálním programu na {y - 1974}. Letní filmové škole Uherské Hradiště ({y})."
            m_id = gen_id()
            cur.execute("""
                INSERT INTO movies (id, created, updated, title_cz, title_en, director, year, duration_minutes, section, synopsis, photo, status, is_published, festival_year)
                VALUES (?, ?, ?, ?, ?, '', ?, ?, ?, ?, '', 'Confirmed', 1, ?)
            """, (m_id, now, now, title, title_en, py, dur, sec, syn, y))
            c += 1
        return c

    c24 = import_hist('starbase_dumps/raw_films_2024.json', 2024)
    c25 = import_hist('starbase_dumps/raw_films_2025.json', 2025)
    print(f"  ✅ Vloženo {c24} archivních filmů (2024) a {c25} archivních filmů (2025).")

    # 5. GUESTS & STAFF
    print("\n⭐ Vkládám festivalové hosty a štáb...")
    guests_list = [
        ('Agnieszka Holland', 'VIP_A', 'Polsko', 'holland@cinema.pl', '+48 601 234 567', 'Hotel Grand', '101', 'Čestná hostka LFŠ, režisérka'),
        ('Jiří Mádl', 'VIP_A', 'Česká republika', 'madl@film.cz', '+420 602 111 222', 'Hotel Grand', '102', 'Delegace k filmu Vlny'),
        ('Karel Roden', 'VIP_A', 'Česká republika', 'roden@art.cz', '+420 603 333 444', 'Hotel Grand', '103', 'Výroční cena AČFK'),
        ('Iva Hejlíčková', 'DELEGACE', 'Česká republika', 'iva.hejlickova@lfs.cz', '+420 777 222 333', 'Koleje Mojmír', '204', 'Lektorský úvod a diskuze'),
        ('Maciej Gil', 'DELEGACE', 'Polsko', 'maciej.gil@kino.pl', '+48 505 444 333', 'Hotel Grand', '205', 'Dramaturg sekce Fokus: Polsko'),
        ('Yannick Rolandeau', 'DELEGACE', 'Francie', 'yannick@critique.fr', '+33 612 345 678', 'Hotel Grand', '206', 'Zahraniční filmový kritik a porota'),
        ('Petr Vlček', 'DELEGACE', 'Česká republika', 'petr.vlcek@lfs.cz', '+420 739 111 999', 'Koleje Mojmír', '210', 'Odborný lektor a programátor'),
        ('MUDr. Pavel Novák', 'MECENAS', 'Česká republika', 'novak.mecenas@seznam.cz', '+420 608 555 666', 'Hotel Grand', '301', 'Mecenáš LFŠ a člen Klubu přátel'),
        ('Alena Dvořáková', 'MECENAS', 'Česká republika', 'dvorakova.mecenas@gmail.com', '+420 602 777 888', 'Hotel Grand', '302', 'Dlouholetá mecenáška'),
    ]
    for g in guests_list:
        cur.execute("""
            INSERT INTO guests (id, created, updated, full_name, category, country, email, phone, invitation_status, hotel_name, room_number, accommodation_notes)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'CONFIRMED', ?, ?, ?)
        """, (gen_id(), now, now, g[0], g[1], g[2], g[3], g[4], g[5], g[6], g[7]))

    staff = [
        ('Radana Korená', 'Ředitelka festivalu', '+420 603 123 456', 'vedeni', 'K1 - Vedení', 1),
        ('Jan Jílek', 'Programový ředitel', '+420 604 234 567', 'program', 'K2 - Program', 2),
        ('Kateřina Planičková', 'Hlavní dramaturgyně & Koordinátorka programu', '+420 608 345 678', 'program', 'K2 - Program', 3),
        ('Vojtěch Franek', 'Hlavní administrátor StarBase & IT koordinátor', '+420 739 456 789', 'produkce', 'K3 - Produkce', 4),
        ('Eva Finková', 'Koordinátorka překladů a titulků', '+420 732 567 890', 'program', 'K2 - Program', 5),
        ('Vedoucí sálu Hvězda', 'Vedoucí sálové služby – Kino Hvězda', '+420 777 100 001', 'sluzba', 'K4 - Sály', 10),
        ('Vedoucí sálu Reduta', 'Vedoucí sálové služby – Reduta', '+420 777 100 002', 'sluzba', 'K4 - Sály', 11),
        ('Dispečink LFŠ', 'Centrální dispečink dopravy & logistiky', '+420 777 999 888', 'dispecink', 'K5 - Dispečink', 6),
        ('Festivalový lékař', 'Zdravotní služba LFŠ Uherské Hradiště', '+420 777 112 112', 'zdravotnik', 'K1 - Tísňový', 7),
    ]
    # Štábovka lists the current edition's staff members marked for it; each contact is a person on that staff.
    cur.execute("SELECT id FROM editions WHERE is_current = 1")
    current = cur.fetchone()
    if current is None:
        print("⚠️ Žádný ročník není aktuální, Štábovku přeskakuji.")
    else:
        # The contacts below replace their own earlier copies; the rest of the staff is managed in Štáb ročníku.
        cur.executemany(
            "DELETE FROM staff_members WHERE edition = ? AND directory_name = ? AND roles IN ('[]', '')",
            [(current[0], s[0]) for s in staff],
        )
    for s in staff if current else []:
        cur.execute("SELECT id FROM persons WHERE full_name = ? AND phone = ?", (s[0], s[2]))
        found = cur.fetchone()
        person_id = found[0] if found else gen_id()
        if not found:
            cur.execute("""
                INSERT INTO persons (id, created, updated, full_name, phone)
                VALUES (?, ?, ?, ?, ?)
            """, (person_id, now, now, s[0], s[2]))
        cur.execute("""
            INSERT OR IGNORE INTO staff_members (id, created, updated, person, edition, role_title, department, in_directory, directory_name, directory_phone, radio_channel, directory_order)
            VALUES (?, ?, ?, ?, ?, ?, ?, 1, ?, ?, ?, ?)
        """, (gen_id(), now, now, person_id, current[0], s[1], s[3], s[0], s[2], s[4], s[5]))

    # Bulletin
    cur.execute("""
        INSERT INTO bulletin (id, created, updated, title, message, urgency, is_active)
        VALUES (?, ?, ?, 'Vítejte na 52. Letní filmové škole', 'Přípravy festivalu v Uherském Hradišti běží naplno. Sledujte harmonogram projekcí a pokyny pro sálovou službu.', 'Info', 1)
    """, (gen_id(), now, now))

    con.commit()
    con.close()
    print("\n🎉 Hotovo! Databáze byla úspěšně naplněna reálnými daty a správnými festivalovými dny.")

if __name__ == '__main__':
    main()
