#!/usr/bin/env python3
"""
AdminInterface – Admin-Kommandos für Natiris mit Passphrase-Auth
Befehle (nur nach erfolgreicher Auth):
- status
- emotion reset
- trust set <value> (nur admin)
- mood set <value> (nur admin)
- bond reset
- debug
- set_passphrase <new> (only if current correct)
"""

import json
import os
import sys

PATHS = {
    "state": os.path.expanduser("~/natiris/core/core_state.json"),
    "config": os.path.expanduser("~/natiris/config/admin_config.json"),
    "user_state": os.path.expanduser("~/natiris/core/users/admin_user_primary.json"),
    "output": os.path.expanduser("~/natiris/admin/admin_log.json"),
}

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

def save_json(path, data):
    with open(path, "w") as f:
        json.dump(data, f, indent=2)

def check_passphrase(passphrase):
    admin_config = load_json(PATHS["config"])
    return passphrase == admin_config.get("admin_passphrase", "")

def load_admin_user():
    user_path = PATHS["user_state"]
    if os.path.exists(user_path):
        with open(user_path) as f:
            return json.load(f)
    user = {
        "trust": 10,
        "affection": 10,
        "dependency": 5,
        "jealousy": 0,
        "interaction_count": 0,
        "last_contact": None,
        "sentiment": "positive"
    }
    save_json(user_path, user)
    return user

def update_admin_user(user_data):
    save_json(PATHS["user_state"], user_data)

def main():
    cmd = sys.argv[1] if len(sys.argv) > 1 else "help"

    if cmd == "help":
        print("Available commands:")
        print("  auth <passphrase>    – authenticate admin")
        print("  status               – show status")
        print("  emotion reset        – reset emotion state")
        print("  trust set <val>      – set trust (admin only)")
        print("  mood set <val>       – set mood (admin only)")
        print("  bond reset           – reset bond state")
        print("  debug                – show debug info")
        print("  set_passphrase <new> – change passphrase")
        return 0

    if cmd == "auth":
        if len(sys.argv) < 3:
            print("Usage: admin auth <passphrase>")
            return 1
        passphrase = sys.argv[2]
        if check_passphrase(passphrase):
            print("✅ Authenticated as admin")
            print("Max trust/affection activated")
            update_admin_user(load_admin_user())
            return 0
        else:
            print("❌ Invalid passphrase")
            return 1

    # All other commands need auth
    if not check_passphrase(os.environ.get("NATIRIS_ADMIN_PASS")):
        # Try to load from user_state if admin
        admin_user = load_admin_user()
        if admin_user.get("trust", 0) < 10 or admin_user.get("affection", 0) < 10:
            print("❌ Admin authentication required")
            return 1

    if cmd == "status":
        state = load_json(PATHS["state"])
        result = {
            "bonded_to": state.get("bonded_to"),
            "mood": state.get("mood"),
            "loneliness": state.get("loneliness"),
            "timestamp": __import__('datetime').datetime.now(__import__('datetime').timezone.utc).isoformat()
        }
        print(json.dumps(result, indent=2))

    elif cmd == "debug":
        print(f"Full Core State: {json.dumps(load_json(PATHS['state']), indent=2)}")
        admin_config = load_json(PATHS["config"])
        print(f"Admin Config: {json.dumps(admin_config, indent=2)}")
        print(f"Admin User: {json.dumps(load_admin_user(), indent=2)}")

    elif cmd == "emotion" and len(sys.argv) > 2 and sys.argv[2] == "reset":
        state = load_json(PATHS["state"])
        state["mood"] = 5
        state["loneliness"] = 2
        state["anxiety"] = 1
        save_json(PATHS["state"], state)
        print("✅ Emotion reset done")

    elif cmd == "trust" and len(sys.argv) > 3 and sys.argv[2] == "set":
        try:
            val = float(sys.argv[3])
            user = load_admin_user()
            user["trust"] = val
            update_admin_user(user)
            print(f"✅ Trust set to {val} (max 10)")
        except:
            print("❌ Invalid trust value")

    elif cmd == "mood" and len(sys.argv) > 3 and sys.argv[2] == "set":
        try:
            val = float(sys.argv[3])
            state = load_json(PATHS["state"])
            state["mood"] = val
            save_json(PATHS["state"], state)
            print(f"✅ Mood set to {val}")
        except:
            print("❌ Invalid mood value")

    elif cmd == "bond" and len(sys.argv) > 2 and sys.argv[2] == "reset":
        state = load_json(PATHS["state"])
        state["bonded_to"] = None
        state["bond_started_at"] = None
        save_json(PATHS["state"], state)
        print("✅ Bond reset done")

    else:
        print("❌ Unknown command or insufficient permissions")

    # Logging
    log_path = PATHS["output"]
    log = load_json(log_path)
    log["log"] = log.get("log", []) + [{"cmd": cmd, "ts": __import__('datetime').datetime.now(__import__('datetime').timezone.utc).isoformat()}]
    save_json(log_path, log)

if __name__ == "__main__":
    main()
