import json
import sys
import os

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

    # Name ersetzen
    new_name = source.get('name', target.get('name'))
    target['name'] = new_name

    # Beschreibung ergänzen
    source_desc = source.get('description', '')
    target_desc = target.get('description', '')
    if source_desc and target_desc:
        target['description'] = source_desc + "\n\n" + target_desc
    elif source_desc:
        target['description'] = source_desc

    # Trappings ersetzen
    if 'trappings' in source:
        target['trappings'] = source['trappings']

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

    # Labels in Ziel-Effekten ersetzen
    if isinstance(target_effects, list):
        for effect in target_effects:
            if isinstance(effect, dict):
                effect['label'] = new_name
    else:
        warn_ids.append(sid)
        target_effects = []

    # Neue Effekte anhängen
    if isinstance(source_effects, list) and source_effects:
        target_effects.extend(source_effects)
        target['effects'] = target_effects

    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)

    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())

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

    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}")

    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_overwrite.py ziel.json quelle1.json [quelle2.json ...]
if __name__ == "__main__":
    if len(sys.argv) < 3:
        print("Nutzung: python merge_items_with_effects_overwrite.py ziel.json quelle1.json [quelle2.json ...]")
        sys.exit(1)

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