import time
from pathlib import Path

from scripts.tz_utils import get_tz, parse_iso_datetime, to_timezone, format_moscow_ymd_hm, format_stamp_ddmmyyyy_hhmm
from scripts.transform import safe_str, format_money, map_ticket_type_seat_counts, build_rows
from scripts.export import write_csv, write_xlsx


def process_event(*, client, event_id: int, settings, output_dir: Path) -> bool:
    print("\n" + "=" * 70)
    print(f"Processing event {event_id} | timeout={settings.api_timeout}s retries={settings.max_retries}")

    tz = get_tz(settings.output_timezone)

    # 1) event details
    print("\n[1/5] Fetching event details...")
    ev = client.get_event(event_id)
    if not (ev.get("success") and ev.get("data")):
        print(f"Fatal: event details failed for {event_id}: {ev.get('error')}")
        return False

    title = safe_str(ev["data"].get("title"))
    begin_raw = ev["data"].get("beginDate")
    dt = parse_iso_datetime(begin_raw)
    dt_local = to_timezone(dt, tz) if dt else None
    date_str = format_moscow_ymd_hm(dt_local)

    print(f"Event: {title}")
    print(f"Begin (local={settings.output_timezone}): {date_str}")

    # 2) ticket types seat count map
    print("\n[2/5] Fetching ticket types for seat count mapping...")
    ttypes_json = client.get_ticket_types(event_id)
    seat_count_map = map_ticket_type_seat_counts(ttypes_json)
    print(f"✓ Mapped {len(seat_count_map)} ticket types to seat counts")

    # 3) tickets
    print("\n[3/5] Fetching all tickets...")
    try:
        tickets = client.get_all_tickets(event_id)
    except Exception as e:
        print(f"Fatal: ticket fetch failed for {event_id}: {e}")
        return False
    print(f"Total tickets retrieved: {len(tickets)}")

    # 4) orders
    unique_order_ids = list(set(t.get("userOrderId") for t in tickets if t.get("userOrderId")))
    print(f"Unique orders found: {len(unique_order_ids)}")

    print("\n[4/5] Fetching order details...")
    order_info_map, ticket_type_map = client.fetch_order_details(unique_order_ids, format_money, safe_str)
    print(f"Total ticket type IDs mapped: {len(ticket_type_map)}")

    # 5) build rows
    print("\n[5/5] Building output rows...")
    rows, unmapped = build_rows(
        event_title=title,
        event_date_str=date_str,
        tickets=tickets,
        order_info_map=order_info_map,
        ticket_type_map=ticket_type_map,
        ticket_type_seat_count_map=seat_count_map,
        hidden_columns=settings.hidden_columns,
    )

    if unmapped:
        print(f"⚠️  Warning: {unmapped} tickets missing seat count mapping")

    # filenames
    csv_name = f"tickets_event_{event_id}.csv"
    csv_path = output_dir / csv_name

    stamp = format_stamp_ddmmyyyy_hhmm(dt_local)
    if stamp:
        if settings.include_event_id_in_xlsx_name:
            xlsx_name = f"{stamp}_{event_id}.xlsx"
            sheet_name = f"{stamp}_{event_id}"
        else:
            xlsx_name = f"{stamp}.xlsx"
            sheet_name = stamp
    else:
        xlsx_name = f"event_{event_id}.xlsx"
        sheet_name = f"event_{event_id}"

    xlsx_path = output_dir / xlsx_name

    # export (overwrite)
    write_csv(csv_path, rows, settings.output_columns)
    write_xlsx(xlsx_path, rows, settings.output_columns, sheet_name=sheet_name)

    print(f"\n✓ Wrote CSV : {csv_path}")
    print(f"✓ Wrote XLSX: {xlsx_path}")

    return True

