import argparse
import sys
import time
from pathlib import Path

from config import get_settings, build_headers
from scripts.api_client import RadarioClient
from scripts.export import ensure_output_dir
from scripts.runner import process_event


def main():
    settings = get_settings()
    headers = build_headers(settings)

    parser = argparse.ArgumentParser(
        description="Export Radario tickets for one or more events to CSV + XLSX."
    )
    parser.add_argument(
        "event_ids",
        nargs="*",
        type=int,
        help=f"One or more event IDs. If omitted, uses DEFAULT_EVENT_ID={settings.default_event_id}."
    )
    args = parser.parse_args()
    event_ids = args.event_ids if args.event_ids else [settings.default_event_id]

    root = Path(__file__).resolve().parent
    output_dir = ensure_output_dir(root, settings.output_dir)

    client = RadarioClient(
        headers=headers,
        timeout=settings.api_timeout,
        max_retries=settings.max_retries,
        sleep_between_pages=settings.sleep_between_pages,
        sleep_between_orders=settings.sleep_between_orders,
    )

    ok = 0
    fail = 0

    for i, event_id in enumerate(event_ids, start=1):
        success = process_event(client=client, event_id=event_id, settings=settings, output_dir=output_dir)
        if success:
            ok += 1
        else:
            fail += 1

        if i != len(event_ids):
            time.sleep(settings.sleep_between_events)

    print("\n" + "=" * 70)
    print(f"Done. Successful: {ok} | Failed: {fail} | Output: {output_dir}")
    sys.exit(0 if fail == 0 else 2)


if __name__ == "__main__":
    main()

