#!/usr/bin/env python3
"""
Killt 'Christophorus' und 'OEAMTC/ÖAMTC' aus audio-texts.json.
Ersetzt mit Ortsname + NATO-Callsign aus heli-callsigns.json.

Logik:
  - 'ÖAMTC Christophorus <wort/zahl>'  → '<nato>'         (z.B. 'X-Ray Echo November')
  - 'Christophorus <wort/zahl>' allgemein → '<nato>'
  - SONDERFALL r_mission_start_mN:  '<Station>, <nato>'  (Ort wird genannt — Mission-Opening)
    Ausnahme: wenn Station == Tower-Prefix (z.B. Innsbruck/Innsbruck Tower) -> nur '<nato>'

Schreibt audio-texts.json (Backup: audio-texts.json.bak-pre-christo-kill).
Berührt KEINE MP3s.
"""
import json, re, os, shutil, sys

REPO = 'C:/xampp/htdocs/geograsim/App/sims/heli'
TEXTS_FILE = REPO + '/scripts/audio-texts.json'
CALLSIGNS_FILE = REPO + '/data/heli-callsigns.json'
BAK = TEXTS_FILE + '.bak-pre-christo-kill'

with open(TEXTS_FILE, 'r', encoding='utf-8') as f:
    texts = json.load(f)
with open(CALLSIGNS_FILE, 'r', encoding='utf-8') as f:
    cs = json.load(f)

mapping = cs['mapping']
z2h = cs['_zahl_zu_helikey']

z2h_clean = {k: v for k, v in z2h.items() if not k.startswith('_')}
word_to_h = {k.lower(): v for k, v in z2h_clean.items()}
digits_word = {'eins':'1','zwei':'2','drei':'3','vier':'4','fuenf':'5',
               'sechs':'6','sieben':'7','acht':'8','neun':'9','zehn':'10',
               'elf':'11','zwoelf':'12','vierzehn':'14','sechzehn':'16'}
digit_to_h = {}
for w, h in z2h_clean.items():
    digit_to_h[digits_word[w]] = h

if not os.path.exists(BAK):
    shutil.copy(TEXTS_FILE, BAK)
    print(f'Backup -> {BAK}')

def normalize(s):
    return s.lower().replace('ä','ae').replace('ö','oe').replace('ü','ue').replace('ß','ss')

def lookup(token):
    t = normalize(token)
    if t in word_to_h:
        return word_to_h[t]
    if token in digit_to_h:
        return digit_to_h[token]
    return None

def replace_one(aid, text):
    if 'Christophorus' not in text and 'ÖAMTC' not in text and 'OEAMTC' not in text:
        return text, 0
    count = 0
    is_mission_start = aid.startswith('r_mission_start_')

    def repl_oeamtc_christo(m):
        nonlocal count
        token = m.group(1)
        h = lookup(token)
        if not h or h not in mapping:
            return m.group(0)
        count += 1
        return mapping[h]['nato']

    def repl_christo(m):
        nonlocal count
        token = m.group(1)
        h = lookup(token)
        if not h or h not in mapping:
            return m.group(0)
        count += 1
        st = mapping[h]['station']
        nato = mapping[h]['nato']
        tower = mapping[h]['tower']
        if is_mission_start:
            tower_prefix = tower.split()[0]
            if st.split()[0] != tower_prefix:
                return f'{st}, {nato}'
        return nato

    out = re.sub(r'(?:ÖAMTC|OEAMTC)\s+Christophorus\s+([0-9]+|[A-Za-zÄÖÜäöüß]+)', repl_oeamtc_christo, text)
    out = re.sub(r'Christophorus\s+([0-9]+|[A-Za-zÄÖÜäöüß]+)', repl_christo, out)
    # Reste-Cleanup: '(ÖAMTC)' Klammer-Annotation entfernen, plus doppelte Spaces fixen
    before = out
    out = re.sub(r'\s*\((?:ÖAMTC|OEAMTC)\)', '', out)
    if out != before:
        count += 1
    out = re.sub(r'  +', ' ', out)
    return out, count

total = 0
changed = []
for aid, txt in list(texts.items()):
    if aid.startswith('_'):
        continue
    if not isinstance(txt, str):
        continue
    new_txt, n = replace_one(aid, txt)
    if n > 0:
        texts[aid] = new_txt
        total += n
        changed.append(aid)

with open(TEXTS_FILE, 'w', encoding='utf-8') as f:
    json.dump(texts, f, indent=2, ensure_ascii=False)

print(f'Ersetzungen: {total} in {len(changed)} Eintraegen\n')
print('--- Beispiele ---')
samples = ['r_mission_start_m1','r_mission_start_m2','r_mission_start_m4','r_mission_start_m17',
           'r_nav_heli_intro_c8','r_pilot_call_c8','r_tower_approach_c1','r_tower_extract_c1',
           'r_tower_geo_m1','r_tower_handover_c8','r_tower_start_c8','r_tower_strike_c6',
           'r_wp_geo_graz_c12','r_wp_geo_klagenfurt_c11']
for s in samples:
    if s in texts:
        print(f'  {s}:')
        print(f'    {texts[s][:200]}')
