"""
Загрузка треков SVO рейсов и сборка финального датасета.
"""
import requests, json, time, os, sys
from dotenv import load_dotenv
from noise_model import calc_zone_radii_for_point

load_dotenv(dotenv_path='.env')
KEY = os.getenv('FLIGHTRADAR24_API_KEY')
BASE = 'https://fr24api.flightradar24.com/api'
HEADERS = {'Authorization': f'Bearer {KEY}', 'Accept': 'application/json', 'Accept-Version': 'v1'}

BOUNDS = {'lat_min': 54.0, 'lat_max': 57.0, 'lon_min': 35.5, 'lon_max': 40.5}
def in_mo(lat, lon):
    return BOUNDS['lat_min'] <= lat <= BOUNDS['lat_max'] and BOUNDS['lon_min'] <= lon <= BOUNDS['lon_max']

with open('data/raw_svo_2026-03-21.json') as f:
    raw = json.load(f)

flights_raw = raw['flights']
print(f'📡 Загружаем треки для {len(flights_raw)} SVO рейсов...')
os.makedirs('data/cache_svo', exist_ok=True)

flights_final = []
errors = 0

for i, flight in enumerate(flights_raw):
    fid = flight['id']
    cache = f'data/cache_svo/track_{fid}.json'

    if os.path.exists(cache):
        with open(cache) as f:
            tracks = json.load(f)
    else:
        r = requests.get(f'{BASE}/flight-tracks', headers=HEADERS,
            params={'flight_id': fid}, timeout=20)
        if r.status_code == 429:
            print(f'  ⏳ 429 на {i}, пауза 30с...')
            time.sleep(30)
            r = requests.get(f'{BASE}/flight-tracks', headers=HEADERS,
                params={'flight_id': fid}, timeout=20)
        if not r.ok:
            errors += 1
            continue
        raw_r = r.json()
        tracks = raw_r[0].get('tracks', []) if isinstance(raw_r, list) and raw_r else []
        with open(cache, 'w') as f:
            json.dump(tracks, f)
        time.sleep(1.2)

    # Фильтруем точки — только над МО
    mo_pts = sorted([p for p in tracks if in_mo(p.get('lat',0), p.get('lon',0))],
                    key=lambda p: p.get('timestamp',''))
    if len(mo_pts) < 2:
        continue

    points = []
    for pt in mo_pts:
        alt_ft = pt.get('alt', 0) or 0
        alt_m  = round(alt_ft / 3.28084)
        points.append({
            'lat': pt['lat'], 'lon': pt['lon'],
            'altitude': alt_ft, 'altitude_m': alt_m,
            'speed': pt.get('gspeed', 0), 'heading': pt.get('track', 0),
            'timestamp': pt.get('timestamp', ''),
            'zone_radii': calc_zone_radii_for_point(alt_m),
        })

    flights_final.append({
        'id':            fid,
        'callsign':      flight['callsign'],
        'flight_number': flight['flight_number'],
        'aircraft_type': flight['aircraft_type'],
        'registration':  flight['registration'],
        'airline':       flight.get('callsign','')[:3],
        'origin':        flight['origin'],
        'destination':   flight['destination'],
        'orig_icao':     flight['orig_icao'],
        'dest_icao':     flight['dest_icao'],
        'type':          'departure' if flight['orig_icao'] == 'UUEE' else 'arrival',
        'points':        points,
    })

    if (i+1) % 5 == 0:
        print(f'  {i+1}/{len(flights_raw)}: {len(flights_final)} рейсов с треками')

print(f'\n✅ Готово: {len(flights_final)} рейсов, ошибок: {errors}')

dataset = {
    'generated_at': '2026-03-22T18:00:00Z',
    'description':  'Реальные треки FR24 за 21 марта 2026, SVO, Московская область',
    'region':       'Московская область',
    'date':         '2026-03-21',
    'source':       'flightradar24_production',
    'airports': {
        'SVO': {'lat': 55.9726, 'lon': 37.4146, 'name': 'Шереметьево'},
        'DME': {'lat': 55.4088, 'lon': 37.9063, 'name': 'Домодедово'},
        'VKO': {'lat': 55.5914, 'lon': 37.2615, 'name': 'Внуково'},
        'ZIA': {'lat': 55.5531, 'lon': 38.1500, 'name': 'Жуковский'},
    },
    'flights_count': len(flights_final),
    'flights':       flights_final,
}

with open('data/sample_flights.json', 'w', encoding='utf-8') as f:
    json.dump(dataset, f, ensure_ascii=False)

total_pts = sum(len(f['points']) for f in flights_final)
print(f'📍 Точек над МО: {total_pts}')
print('💾 data/sample_flights.json обновлён\n')
for flt in flights_final[:8]:
    pts = flt['points']
    direction = '🛫' if flt['type'] == 'departure' else '🛬'
    print(f"  {direction} {flt['flight_number']:8} {flt['aircraft_type']:5} "
          f"{flt['origin']:3}→{flt['destination']:3} | "
          f"{len(pts):3} точек | alt {pts[0]['altitude_m']}..{pts[-1]['altitude_m']}м")
