#!/usr/bin/env python3
"""
OrchestratorAll – führt alle natiris Core-Module nacheinander aus
speichert Gesamtoutput in natiris_full_state.json
"""

import json
import subprocess
import os
from datetime import datetime, timezone

CORE_DIR = os.path.expanduser("~/natiris/core")

MODULES = [
    ("EmotionEngine", "emotion_delta.json", "Emotion"),
    ("MaturityEngine", "maturity_output.json", "Maturity"),
    ("BondEngine", "bond_output.json", "Bond"),
    ("InnerLifeWorker", "inner_life_log.json", "InnerLife"),
    ("ExpressionEngine", "expression_bias.json", "Expression"),
]

def run_module(name):
    cmd = ["python3", f"{CORE_DIR}/{name}.py"]
    result = subprocess.run(cmd, capture_output=True, text=True)
    return result.returncode == 0, result.stdout, result.stderr

def main():
    print("Natiris Core – Full Orchestrator")
    print("=" * 40)

    full_state = {
        "timestamp": datetime.now(timezone.utc).isoformat(),
        "modules": {}
    }

    for engine_name, output_file, alias in MODULES:
        ok, out, err = run_module(engine_name)
        if ok:
            print(f"✅ {engine_name}: OK")
            # Output laden
            output_path = f"{CORE_DIR}/{output_file}"
            if os.path.exists(output_path):
                with open(output_path) as f:
                    full_state["modules"][alias] = json.load(f)
        else:
            print(f"❌ {engine_name}: FAILED\n{err}")

    full_state["modules"]["core_state"] = load_json_file(f"{CORE_DIR}/core_state.json")
    full_path = f"{CORE_DIR}/natiris_full_state.json"
    with open(full_path, "w") as f:
        json.dump(full_state, f, indent=2)

    print("\n— Full State —")
    print(json.dumps(full_state, indent=2))

def load_json_file(path):
    try:
        with open(path) as f:
            return json.load(f)
    except Exception:
        return {}

if __name__ == "__main__":
    main()
