#!/usr/bin/env python3
"""
Fluggesellschaft — Initiale Daten-Migration.

Zieht alle L4-Aufträge aus busfahrt/assets/data/orders.json und alle dort
referenzierten Städte aus busfahrt/assets/data/cities.json in den
fluggesellschaft-Daten-Ordner. Plus Asien-Städte ergänzen (Lücke aus L4).

Anschließend werden die Aufträge auf level='l1'/'l2'/'l3' verteilt
(grobe Heuristik: Nordamerika/Europa-nah = L1, Lateinamerika/Afrika = L2,
Rest Welt + Asien = L3).

Idempotent — erstellt orders.json + cities.json neu jedes Mal.
"""

import json
from pathlib import Path

ROOT = Path(__file__).resolve().parents[3]  # App/
BUS_DATA = ROOT / "sims" / "busfahrt" / "assets" / "data"
FLY_DATA = ROOT / "sims" / "fluggesellschaft" / "assets" / "data"
FLY_DATA.mkdir(parents=True, exist_ok=True)

# Asien-Ergänzungen (Lücke aus L4)
ASIA_CITIES = [
    {
        "id": "tokio", "title": "Tokio", "country": "Japan", "isCapital": True,
        "lat": 35.6762, "lon": 139.6503, "population_million": 13.96,
        "continent": "Asien", "timezone": "Asia/Tokyo", "utcOffset": 9,
        "infoText": {
            "de": "Tokio ist die Hauptstadt Japans und mit fast 14 Mio. Einwohnern in der Stadt selbst (und über 37 Mio. im Großraum) die einwohnerreichste Metropolregion der Welt. Bekannt für Sushi, Kirschblüten, Anime, das Kaiserschloss und die Shibuya-Kreuzung.",
            "easy": "Tokio ist die Hauptstadt von Japan. Tokio ist die größte Stadt der Welt. Hier gibt es viel Technik und schöne Kirschblüten."
        },
        "imagePath": "assets/cities/tokio.png", "level": 3
    },
    {
        "id": "peking", "title": "Peking", "country": "China", "isCapital": True,
        "lat": 39.9042, "lon": 116.4074, "population_million": 21.54,
        "continent": "Asien", "timezone": "Asia/Shanghai", "utcOffset": 8,
        "infoText": {
            "de": "Peking (chinesisch Beijing) ist die Hauptstadt der Volksrepublik China. Über 21 Mio. Einwohner. Heimat der Verbotenen Stadt, des Tiananmen-Platzes und in der Nähe der Großen Mauer.",
            "easy": "Peking ist die Hauptstadt von China. China hat sehr viele Menschen. In der Nähe von Peking ist die Große Mauer."
        },
        "imagePath": "assets/cities/peking.png", "level": 3
    },
    {
        "id": "delhi", "title": "Delhi", "country": "Indien", "isCapital": True,
        "lat": 28.6139, "lon": 77.2090, "population_million": 33.81,
        "continent": "Asien", "timezone": "Asia/Kolkata", "utcOffset": 5.5,
        "infoText": {
            "de": "Delhi (offiziell New Delhi für den Regierungssitz) ist die Hauptstadt Indiens. Mit 33 Mio. Einwohnern im Großraum die zweitgrößte Metropolregion der Welt nach Tokio. Sehr alte Kultur, Mughal-Architektur (Rotes Fort), Hindu- und Muslim-Heiligtümer.",
            "easy": "Delhi ist die Hauptstadt von Indien. Delhi hat sehr viele Menschen. Indien ist ein großes Land in Asien."
        },
        "imagePath": "assets/cities/delhi.png", "level": 3
    },
    {
        "id": "bangkok", "title": "Bangkok", "country": "Thailand", "isCapital": True,
        "lat": 13.7563, "lon": 100.5018, "population_million": 10.54,
        "continent": "Asien", "timezone": "Asia/Bangkok", "utcOffset": 7,
        "infoText": {
            "de": "Bangkok ist die Hauptstadt Thailands. Bekannt für goldene Tempel (Wat Pho, Wat Arun), den Königspalast und das Verkehrschaos. Wichtiges Tourismus-Drehkreuz Südostasiens.",
            "easy": "Bangkok ist die Hauptstadt von Thailand. In Bangkok gibt es viele goldene Tempel."
        },
        "imagePath": "assets/cities/bangkok.png", "level": 2
    },
    {
        "id": "singapur", "title": "Singapur", "country": "Singapur", "isCapital": True,
        "lat": 1.3521, "lon": 103.8198, "population_million": 5.69,
        "continent": "Asien", "timezone": "Asia/Singapore", "utcOffset": 8,
        "infoText": {
            "de": "Singapur ist ein Stadtstaat in Südostasien — eine Insel-Republik, die zugleich Land und Stadt ist. Wichtigster Hafen Asiens, finanzielles Zentrum, bekannt für die Marina Bay Sands, den Botanischen Garten und strenge Sauberkeits-Gesetze.",
            "easy": "Singapur ist eine Stadt und ein Land zugleich. Singapur ist eine Insel. Hier ist es sehr sauber und modern."
        },
        "imagePath": "assets/cities/singapur.png", "level": 2
    },
    {
        "id": "seoul", "title": "Seoul", "country": "Südkorea", "isCapital": True,
        "lat": 37.5665, "lon": 126.9780, "population_million": 9.78,
        "continent": "Asien", "timezone": "Asia/Seoul", "utcOffset": 9,
        "infoText": {
            "de": "Seoul ist die Hauptstadt Südkoreas, am Fluss Han. Bekannt für K-Pop, Samsung, LG, Hyundai — Technologie-Welthauptstadt. Die Grenze nach Nordkorea (DMZ) ist nur 50 km entfernt.",
            "easy": "Seoul ist die Hauptstadt von Südkorea. In Seoul kommen viele K-Pop-Stars her. Die Grenze zu Nordkorea ist nicht weit weg."
        },
        "imagePath": "assets/cities/seoul.png", "level": 3
    },
    {
        "id": "jakarta", "title": "Jakarta", "country": "Indonesien", "isCapital": True,
        "lat": -6.2088, "lon": 106.8456, "population_million": 10.56,
        "continent": "Asien", "timezone": "Asia/Jakarta", "utcOffset": 7,
        "infoText": {
            "de": "Jakarta ist die Hauptstadt Indonesiens auf der Insel Java. Indonesien ist der größte Inselstaat der Welt mit über 17.000 Inseln. Jakarta versinkt langsam (Bodensenkung 25 cm/Jahr) — daher wird gerade eine neue Hauptstadt namens Nusantara auf Borneo gebaut.",
            "easy": "Jakarta ist die Hauptstadt von Indonesien. Indonesien besteht aus vielen Inseln. Jakarta versinkt langsam. Bald wird die Hauptstadt umziehen."
        },
        "imagePath": "assets/cities/jakarta.png", "level": 3
    },
]

# Asien-Aufträge (Auftragstypen A = direkt, B = Hauptstadt-Frage, D = Detail)
ASIA_ORDERS = [
    # Tokio
    {"id": "fl-l3-a-tokio", "level": "l3", "type": "A", "cityId": "tokio",
     "prompt": {"de": "Flug nach Tokio — Hauptstadt Japans, größte Metropolregion der Welt.",
                "easy": "Flieg nach Tokio. Tokio ist die Hauptstadt von Japan."},
     "tariffPerKm": 0.18, "fixedFee": 800},
    {"id": "fl-l3-b-japan", "level": "l3", "type": "B", "cityId": "tokio",
     "prompt": {"de": "Bringe die Gruppe in die Hauptstadt Japans. Wie heißt diese Stadt?",
                "easy": "Flieg in die Hauptstadt von Japan. Wie heißt die Stadt?"},
     "choices": ["tokio", "peking", "seoul"], "tariffPerKm": 0.18, "fixedFee": 800},
    {"id": "fl-l3-d-tokio-sushi", "level": "l3", "type": "D", "cityId": "tokio",
     "prompt": {"de": "Flug in die asiatische Metropole, Heimat von Sushi und Anime, mit der berühmtesten Fußgänger-Kreuzung der Welt (Shibuya).",
                "easy": "Flieg in die Stadt mit den vielen Lichtern, wo Sushi und Anime herkommen."},
     "tariffPerKm": 0.18, "fixedFee": 800},
    # Peking
    {"id": "fl-l3-a-peking", "level": "l3", "type": "A", "cityId": "peking",
     "prompt": {"de": "Flug nach Peking — Hauptstadt Chinas, nahe der Großen Mauer.",
                "easy": "Flieg nach Peking. Peking ist die Hauptstadt von China."},
     "tariffPerKm": 0.18, "fixedFee": 800},
    {"id": "fl-l3-b-china", "level": "l3", "type": "B", "cityId": "peking",
     "prompt": {"de": "Du sollst in die Hauptstadt Chinas fliegen. Wie heißt diese Stadt?",
                "easy": "Flieg in die Hauptstadt von China. Wie heißt die Stadt?"},
     "choices": ["peking", "tokio", "delhi"], "tariffPerKm": 0.18, "fixedFee": 800},
    {"id": "fl-l3-d-peking-mauer", "level": "l3", "type": "D", "cityId": "peking",
     "prompt": {"de": "Flug in die chinesische Hauptstadt — bekannt für die Verbotene Stadt und die Nähe zur Großen Mauer.",
                "easy": "Flieg in die chinesische Stadt mit der berühmten Großen Mauer in der Nähe."},
     "tariffPerKm": 0.18, "fixedFee": 800},
    # Delhi
    {"id": "fl-l3-a-delhi", "level": "l3", "type": "A", "cityId": "delhi",
     "prompt": {"de": "Flug nach Delhi — Hauptstadt Indiens, zweitgrößte Metropolregion der Welt.",
                "easy": "Flieg nach Delhi. Delhi ist die Hauptstadt von Indien."},
     "tariffPerKm": 0.18, "fixedFee": 800},
    {"id": "fl-l3-b-indien", "level": "l3", "type": "B", "cityId": "delhi",
     "prompt": {"de": "Bringe die Gruppe in die Hauptstadt Indiens. Wie heißt diese Stadt?",
                "easy": "Flieg in die Hauptstadt von Indien. Wie heißt die Stadt?"},
     "choices": ["delhi", "bangkok", "jakarta"], "tariffPerKm": 0.18, "fixedFee": 800},
    # Bangkok
    {"id": "fl-l2-a-bangkok", "level": "l2", "type": "A", "cityId": "bangkok",
     "prompt": {"de": "Flug nach Bangkok — Hauptstadt Thailands mit goldenen Tempeln.",
                "easy": "Flieg nach Bangkok. Bangkok ist die Hauptstadt von Thailand."},
     "tariffPerKm": 0.18, "fixedFee": 800},
    {"id": "fl-l2-b-thailand", "level": "l2", "type": "B", "cityId": "bangkok",
     "prompt": {"de": "Du sollst in die Hauptstadt Thailands fliegen. Wie heißt diese Stadt?",
                "easy": "Flieg in die Hauptstadt von Thailand. Wie heißt die Stadt?"},
     "choices": ["bangkok", "jakarta", "singapur"], "tariffPerKm": 0.18, "fixedFee": 800},
    # Singapur
    {"id": "fl-l2-a-singapur", "level": "l2", "type": "A", "cityId": "singapur",
     "prompt": {"de": "Flug nach Singapur — Inselstaat und einer der wichtigsten Häfen Asiens.",
                "easy": "Flieg nach Singapur. Singapur ist eine Insel und eine Stadt."},
     "tariffPerKm": 0.18, "fixedFee": 800},
    {"id": "fl-l2-d-singapur-stadtstaat", "level": "l2", "type": "D", "cityId": "singapur",
     "prompt": {"de": "Flug in den asiatischen Stadtstaat — die einzige Insel-Republik, die zugleich Stadt und Land ist.",
                "easy": "Flieg in die kleine Insel, die ein eigenes Land ist."},
     "tariffPerKm": 0.18, "fixedFee": 800},
    # Seoul
    {"id": "fl-l3-a-seoul", "level": "l3", "type": "A", "cityId": "seoul",
     "prompt": {"de": "Flug nach Seoul — Hauptstadt Südkoreas, Heimat von K-Pop und Samsung.",
                "easy": "Flieg nach Seoul. Seoul ist die Hauptstadt von Südkorea."},
     "tariffPerKm": 0.18, "fixedFee": 800},
    {"id": "fl-l3-b-suedkorea", "level": "l3", "type": "B", "cityId": "seoul",
     "prompt": {"de": "Bringe die Gruppe in die Hauptstadt Südkoreas. Wie heißt diese Stadt?",
                "easy": "Flieg in die Hauptstadt von Südkorea. Wie heißt die Stadt?"},
     "choices": ["seoul", "tokio", "peking"], "tariffPerKm": 0.18, "fixedFee": 800},
    # Jakarta
    {"id": "fl-l3-a-jakarta", "level": "l3", "type": "A", "cityId": "jakarta",
     "prompt": {"de": "Flug nach Jakarta — aktuelle Hauptstadt Indonesiens auf der Insel Java.",
                "easy": "Flieg nach Jakarta. Jakarta ist die Hauptstadt von Indonesien."},
     "tariffPerKm": 0.18, "fixedFee": 800},
    {"id": "fl-l3-d-jakarta-versinkt", "level": "l3", "type": "D", "cityId": "jakarta",
     "prompt": {"de": "Flug in die Hauptstadt, die langsam versinkt — bald wird der Regierungssitz nach Nusantara auf Borneo verlegt.",
                "easy": "Flieg in die Stadt, die langsam im Meer versinkt."},
     "tariffPerKm": 0.18, "fixedFee": 800},
]

# Heuristik für Level-Verteilung der bestehenden L4-Aufträge:
# L1 (Fluggesellschaft) = Nordamerika + Australien (für Schüler relativ bekannt)
# L2 = Lateinamerika + Nordafrika + Naher Osten
# L3 = Subsahara-Afrika + Asien (weniger bekannt)
L1_COUNTRIES = {"USA", "Kanada", "Australien", "Neuseeland"}
L2_COUNTRIES = {"Brasilien", "Argentinien", "Mexiko", "Kuba", "Ecuador", "Kolumbien",
                "Peru", "Bolivien", "Chile", "Marokko", "Tunesien", "Ägypten"}
# L3 = alles andere

def main():
    with (BUS_DATA / "orders.json").open(encoding="utf-8") as f:
        all_orders = json.load(f)
    with (BUS_DATA / "cities.json").open(encoding="utf-8") as f:
        all_cities = json.load(f)
    cities_by_id = {c["id"]: c for c in all_cities}

    # L4-Aufträge extrahieren
    l4_orders = [o for o in all_orders if o.get("level") == "l4"]
    print(f"Migriere {len(l4_orders)} L4-Aufträge von Busfahrt.")

    # Aufträge nach neuen Levels umsortieren
    migrated = []
    for o in l4_orders:
        city = cities_by_id.get(o["cityId"])
        if not city: continue
        country = city["country"]
        if country in L1_COUNTRIES: new_level = "l1"
        elif country in L2_COUNTRIES: new_level = "l2"
        else: new_level = "l3"
        new_o = dict(o)
        new_o["level"] = new_level
        # ID umlabeln: l1-a-paris → fl-l1-a-paris (klarere Trennung)
        if not new_o["id"].startswith("fl-"):
            new_o["id"] = "fl-" + new_o["id"]
        migrated.append(new_o)

    # Asien-Aufträge anhängen
    migrated.extend(ASIA_ORDERS)

    # Cities-Pool für genutzte Städte zusammenstellen
    used_city_ids = {o["cityId"] for o in migrated}
    for o in migrated:
        if "choices" in o:
            used_city_ids.update(o["choices"])
    cities_out = []
    for cid in used_city_ids:
        if cid in cities_by_id:
            c = dict(cities_by_id[cid])
            # imagePath umstellen falls auf busfahrt-relativ → absolute Busfahrt-Pfade nutzen
            ip = c.get("imagePath", "")
            if ip.startswith("../logistik/"):
                # Logistik-Bilder via busfahrt-Pfad referenzieren
                c["imagePath"] = "../busfahrt/assets/data/" + ip
            elif ip.startswith("../"):
                c["imagePath"] = "../busfahrt/" + ip.lstrip("./")
            cities_out.append(c)
    # Asien-Städte ergänzen (die nicht in busfahrt drin sind)
    asia_ids = {c["id"] for c in ASIA_CITIES}
    bus_ids = {c["id"] for c in cities_out}
    for ac in ASIA_CITIES:
        if ac["id"] not in bus_ids:
            cities_out.append(ac)

    # Sortieren für Stabilität
    cities_out.sort(key=lambda c: c["id"])
    migrated.sort(key=lambda o: (o["level"], o["id"]))

    # Schreiben
    with (FLY_DATA / "orders.json").open("w", encoding="utf-8") as f:
        json.dump(migrated, f, ensure_ascii=False, indent=2)
        f.write("\n")
    with (FLY_DATA / "cities.json").open("w", encoding="utf-8") as f:
        json.dump(cities_out, f, ensure_ascii=False, indent=2)
        f.write("\n")

    levels = {}
    for o in migrated:
        levels[o["level"]] = levels.get(o["level"], 0) + 1
    print("Aufträge: " + ", ".join(f"{k}={v}" for k, v in sorted(levels.items())))
    print(f"Städte:   {len(cities_out)}")
    print(f"OK -- {FLY_DATA}/orders.json + cities.json geschrieben.")

if __name__ == "__main__":
    main()
