#!/usr/bin/env python3
"""
Загрузка всех рейсов SVO (UUEE) за сегодня через FR24 Flight Summary API
Шаг 1: Скачать список всех рейсов (прилёт + вылет)
"""

import os
import sys
import json
import time
from datetime import datetime, timezone, timedelta
from pathlib import Path

API_KEY = os.getenv("FLIGHTRADAR24_API_KEY")
if not API_KEY:
    raise ValueError("FLIGHTRADAR24_API_KEY не найден в окружении (проверь ~/.openclaw/.env)")
BASE_URL = "https://fr24api.flightradar24.com/api"
DATA_DIR = Path(__file__).parent / "data" / "svo_flights"
DATA_DIR.mkdir(parents=True, exist_ok=True)

HEADERS = {
    "Authorization": f"Bearer {API_KEY}",
    "Accept": "application/json",
    "Accept-Version": "v1",
}


def fetch_flights_batch(dt_from: str, dt_to: str, sort: str = "asc", limit: int = 20) -> list:
    """Загрузка одной порции рейсов через curl (Cloudflare не пускает urllib)"""
    import subprocess
    import urllib.parse
    params = {
        "flight_datetime_from": dt_from,
        "flight_datetime_to": dt_to,
        "airports": "both:UUEE",
        "limit": str(limit),
        "sort": sort,
    }
    url = f"{BASE_URL}/flight-summary/light?" + urllib.parse.urlencode(params)
    cmd = [
        "curl", "-s",
        "-H", f"Authorization: Bearer {API_KEY}",
        "-H", "Accept: application/json",
        "-H", "Accept-Version: v1",
        url,
    ]
    r = subprocess.run(cmd, capture_output=True, text=True, timeout=30)
    if r.returncode != 0:
        raise RuntimeError(f"curl failed: {r.stderr}")
    data = json.loads(r.stdout)
    return data.get("data", [])


def fetch_all_flights_for_date(date_str: str) -> list:
    """
    Загрузка всех рейсов за день с пагинацией.
    Стратегия: разбиваем на 2-часовые окна, внутри каждого — пагинация через first_seen.
    """
    all_flights = {}  # fr24_id -> flight_data (дедупликация)
    dt_base = datetime.strptime(date_str, "%Y-%m-%d").replace(tzinfo=timezone.utc)

    for hour_start in range(0, 24, 2):
        hour_end = min(hour_start + 2, 24)
        if hour_end == 24:
            dt_to = f"{date_str}T23:59:59"
        else:
            dt_to = f"{date_str}T{hour_end:02d}:00:00"

        dt_from = f"{date_str}T{hour_start:02d}:00:00"
        last_first_seen = None

        while True:
            # Если есть last_first_seen — сдвигаем окно
            current_from = last_first_seen if last_first_seen else dt_from

            try:
                batch = fetch_flights_batch(current_from, dt_to, sort="asc", limit=20)
            except Exception as e:
                print(f"  Ошибка API ({current_from} — {dt_to}): {e}", file=sys.stderr)
                break

            if not batch:
                break

            new_count = 0
            for f in batch:
                fid = f.get("fr24_id")
                if fid and fid not in all_flights:
                    all_flights[fid] = f
                    new_count += 1

            # Пагинация: если вернулся полный батч (20), берём last first_seen
            if len(batch) >= 20:
                last_first_seen = batch[-1].get("first_seen")
                if not last_first_seen:
                    break
                # Защита от бесконечного цикла
                if last_first_seen >= dt_to:
                    break
                time.sleep(0.3)
            else:
                break

        loaded = len(all_flights)
        print(f"  {hour_start:02d}:00–{hour_end-1:02d}:59  →  всего загружено: {loaded}")
        time.sleep(0.3)

    return list(all_flights.values())


def classify_flights(flights: list) -> dict:
    """Разделение на прилёты и вылеты"""
    arrivals = [f for f in flights if f.get("dest_icao") == "UUEE" and f.get("orig_icao") != "UUEE"]
    departures = [f for f in flights if f.get("orig_icao") == "UUEE" and f.get("dest_icao") != "UUEE"]
    # Рейсы UUEE→UUEE (round-trip) — редко, но бывает
    both = [f for f in flights if f.get("orig_icao") == "UUEE" and f.get("dest_icao") == "UUEE"]
    # Неклассифицированные
    other = [f for f in flights if f not in arrivals and f not in departures and f not in both]
    return {
        "arrivals": sorted(arrivals, key=lambda x: x.get("first_seen", "")),
        "departures": sorted(departures, key=lambda x: x.get("first_seen", "")),
        "both": both,
        "other": other,
    }


def main():
    date_str = sys.argv[1] if len(sys.argv) > 1 else datetime.now(timezone.utc).strftime("%Y-%m-%d")
    print(f"=== Загрузка рейсов SVO за {date_str} ===\n")

    flights = fetch_all_flights_for_date(date_str)
    print(f"\nИтого загружено: {len(flights)} рейсов")

    classified = classify_flights(flights)
    print(f"  Прилёты:   {len(classified['arrivals'])}")
    print(f"  Вылеты:    {len(classified['departures'])}")
    print(f"  Round-trip: {len(classified['both'])}")
    print(f"  Другие:    {len(classified['other'])}")

    # Сохранение
    output_file = DATA_DIR / f"svo_flights_{date_str}.json"
    with open(output_file, "w", encoding="utf-8") as f:
        json.dump({
            "date": date_str,
            "total": len(flights),
            "arrivals": len(classified["arrivals"]),
            "departures": len(classified["departures"]),
            "flights": flights,
            "classified": classified,
        }, f, ensure_ascii=False, indent=2)
    print(f"\nСохранено: {output_file}")

    # Краткая таблица
    print(f"\n{'='*80}")
    print(f"{'#':>3} {'Тип':>4} {'Рейс':>8} {'Маршрут':>20} {'ВВС':>6} {'ТипВС':>6} {'Вылет':>10} {'Прилёт':>10}")
    print(f"{'-'*80}")
    for i, f in enumerate(classified["arrivals"] + classified["departures"], 1):
        ftype = "ARR" if f.get("dest_icao") == "UUEE" else "DEP"
        route = f"{f.get('orig_icao','?')}→{f.get('dest_icao','?')}"
        dep = (f.get("datetime_takeoff") or "")[:10] or "—"
        arr = (f.get("datetime_landed") or "")[:10] or "—"
        print(f"{i:>3} {ftype:>4} {f.get('flight','?'):>8} {route:>20} {f.get('reg','?'):>6} {f.get('type','?'):>6} {dep:>10} {arr:>10}")


if __name__ == "__main__":
    main()
