import json
import sys
import os

# Felder, die ersetzt werden sollen, wenn sie in der Quelle vorhanden sind
REPLACEMENT_FIELDS = [
    "permanent",
    "symptoms",
    "contraction",
    "name",
    "description",
    "durationValue",
    "durationUnit",
    "incubationValue",
    "incubationUnit",
    "results"
]

def merge_entry(target, source, warn_ids):
    sid = source.get("id", "unbekannt")

    # Standardfelder ersetzen
    for field in REPLACEMENT_FIELDS:
        if field in source:
            target[field] = source[field]

    # Effekte bearbeiten
    source_effects = source.get('effects', [])
    target_effects = target.get('effects', [])

    # Effekte vergleichen und nur anhängen, wenn sie unterschiedlich sind
    if isinstance(source_effects, list) and isinstance(target_effects, list):
        for source_effect in source_effects:
            if source_effect not in target_effects:
                target_effects.append(source_effect)

        # Label in Ziel-Effekten aktualisieren
        new_name = source.get("name", target.get("name"))
        for effect in target_effects:
            if isinstance(effect, dict):
                effect["label"] = new_name

        # Aktualisierte Effekte zurückschreiben
        target["effects"] = target_effects

    elif isinstance(source_effects, list):
        # Wenn Ziel keine Liste ist, aber Quelle schon, einfach ersetzen
        target["effects"] = source_effects
    else:
        # Unerwartetes Format protokollieren
        warn_ids.append(sid)

    return target

def merge_files(target_file, source_files, output_file=None, new_ids_log="new_ids.txt", warn_log="warn_ids.txt"):
    with open(target_file, "r", encoding="utf-8") as f:
        target_json = json.load(f)

    target_entries = target_json.get("entries", target_json)
    target_by_id = {entry["id"]: entry for entry in target_entries}
    new_ids = []
    warn_ids = []

    for source_path in source_files:
        print(f"🔄 Verarbeite {source_path} ...")
        with open(source_path, "r", encoding="utf-8") as f:
            source_json = json.load(f)

        source_entries = source_json.get("entries", source_json)

        for source_entry in source_entries:
            sid = source_entry.get("id")
            if not sid:
                print("⚠️  Eintrag ohne ID übersprungen.")
                continue

            if sid in target_by_id:
                target_by_id[sid] = merge_entry(target_by_id[sid], source_entry, warn_ids)
            else:
                target_by_id[sid] = source_entry
                new_ids.append(sid)

    # Ursprungsstruktur beibehalten
    if "entries" in target_json:
        target_json["entries"] = list(target_by_id.values())
        final_output = target_json
    else:
        final_output = list(target_by_id.values())

    # Datei überschreiben
    with open(output_file or target_file, "w", encoding="utf-8") as f:
        json.dump(final_output, f, indent=4, ensure_ascii=False)

    # Neue IDs dokumentieren
    if new_ids:
        with open(new_ids_log, "w", encoding="utf-8") as f:
            f.write("\n".join(new_ids))
        print(f"🆕 {len(new_ids)} neue IDs – siehe {new_ids_log}")

    # Warnungen dokumentieren
    if warn_ids:
        with open(warn_log, "w", encoding="utf-8") as f:
            f.write("\n".join(warn_ids))
        print(f"⚠️ {len(warn_ids)} Items mit ungültigen 'effects' – siehe {warn_log}")

    print(f"📁 Merge abgeschlossen → Datei überschrieben: {target_file}")

# Aufruf: python merge_items_with_effects_deduplicated.py ziel.json quelle1.json [quelle2.json ...]
if __name__ == "__main__":
    if len(sys.argv) < 3:
        print("Nutzung: python merge_items_with_effects_deduplicated.py ziel.json quelle1.json [quelle2.json ...]")
        sys.exit(1)

    target = sys.argv[1]
    sources = sys.argv[2:]
    merge_files(target, sources)
