"""
Загрузка табло аэропорта SVO через Яндекс.Расписания API.
Использование: python3 fetch_tablo.py 2026-03-26
"""
import requests, json, sys, os, time
from datetime import datetime, date
from dotenv import load_dotenv

load_dotenv(dotenv_path='.env')
KEY = os.getenv('YANDEX_RASP_API_KEY')
if not KEY:
    print('❌ YANDEX_RASP_API_KEY не найден в .env')
    sys.exit(1)

TARGET_DATE = sys.argv[1] if len(sys.argv) > 1 else str(date.today())
STATION = 's9600213'  # SVO
BASE = 'https://api.rasp.yandex.net/v3.0/schedule/'

print(f'📅 Загружаем табло SVO за {TARGET_DATE}')

def fetch_page(direction, offset=0):
    params = {
        'apikey': KEY,
        'station': STATION,
        'date': TARGET_DATE,
        'direction': direction,
        'transport_types': 'plane',
        'limit': 100,
        'offset': offset,
        'lang': 'ru_RU',
    }
    r = requests.get(BASE, params=params, timeout=20)
    if r.status_code == 429:
        print('  ⏳ 429, пауза 30с...')
        time.sleep(30)
        r = requests.get(BASE, params=params, timeout=20)
    r.raise_for_status()
    return r.json()

flights = []

for direction in ['departure', 'arrival']:
    offset = 0
    while True:
        data = fetch_page(direction, offset)
        schedules = data.get('schedule', [])
        total = data.get('pagination', {}).get('total', len(schedules))
        
        for item in schedules:
            thread = item.get('thread', {})
            fn = thread.get('number', '')
            cs = fn.replace(' ', '').upper()
            airline_obj = thread.get('carrier', {})
            
            dep = item.get('departure')
            arr = item.get('arrival')
            
            # Для прилётов arrival может быть null — используем departure (вылет из origin)
            time_ref = dep or arr
            
            flights.append({
                'flight_number': fn,
                'callsign': cs,
                'airline': airline_obj.get('title', ''),
                'airline_iata': airline_obj.get('code', ''),
                'airline_icao': airline_obj.get('codes', {}).get('icao'),
                'aircraft': thread.get('vehicle', ''),
                'uid': thread.get('uid', ''),
                'direction': direction,
                'departure': dep,
                'arrival': arr,
                'terminal': item.get('terminal', ''),
                'date': TARGET_DATE,
            })
        
        offset += len(schedules)
        print(f'  {direction}: загружено {offset}/{total}')
        
        if offset >= total or not schedules:
            break
        time.sleep(0.5)

print(f'\n✅ Всего рейсов: {len(flights)}')

# Дедупликация по flight_number + direction
seen = set()
unique = []
for fl in flights:
    key = fl['flight_number'].replace(' ','').upper() + fl['direction']
    if key not in seen:
        seen.add(key)
        unique.append(fl)

print(f'   После дедупликации: {len(unique)}')

# Сохраняем табло
tablo_file = f'data/tablo_SVO_{TARGET_DATE}.json'
with open(tablo_file, 'w', encoding='utf-8') as f:
    json.dump(unique, f, ensure_ascii=False, indent=2)
print(f'💾 {tablo_file}')

# Перезаписываем tablo_need_load.json
out = {'total': len(unique), 'flights': unique}
with open('data/tablo_need_load.json', 'w', encoding='utf-8') as f:
    json.dump(out, f, ensure_ascii=False)
print(f'💾 data/tablo_need_load.json (перезаписан для {TARGET_DATE})')
