#!/usr/bin/env python3
import json
import os
import subprocess
import telnetlib
import time
import urllib.request
from pathlib import Path

REPO_ROOT = Path(__file__).resolve().parents[2]
ROOT = Path.home() / ".timmy" / "evennia" / "timmy_world"
EVENNIA_BIN = Path.home() / ".timmy" / "evennia" / "venv" / "bin" / "evennia"
TIMMY_PASSWORD = os.environ.get("TIMMY_EVENNIA_TIMMY_PASSWORD", "timmy-world-dev")


def shell_json(code: str) -> dict:
    env = dict(**os.environ)
    env["PYTHONPATH"] = str(REPO_ROOT) + ":" + env.get("PYTHONPATH", "")
    result = subprocess.run([str(EVENNIA_BIN), "shell", "-c", code], cwd=ROOT, env=env, capture_output=True, text=True, timeout=120, check=True)
    lines = [line for line in result.stdout.splitlines() if line.strip()]
    return json.loads(lines[-1])


def telnet_roundtrip() -> str:
    tn = telnetlib.Telnet("127.0.0.1", 4000, timeout=10)
    time.sleep(1.0)
    _ = tn.read_very_eager().decode("utf-8", "ignore")
    tn.write(f"connect Timmy {TIMMY_PASSWORD}\n".encode())
    time.sleep(1.0)
    login_out = tn.read_very_eager().decode("utf-8", "ignore")
    tn.write(b"look\n")
    time.sleep(0.6)
    look_out = tn.read_very_eager().decode("utf-8", "ignore")
    tn.close()
    return " ".join((login_out + "\n" + look_out).split())[:600]


def main():
    result = {"game_dir_exists": ROOT.exists()}
    try:
        with urllib.request.urlopen("http://127.0.0.1:4001", timeout=10) as r:
            result["web_status"] = r.status
            result["web_content_type"] = r.headers.get("Content-Type")
    except Exception as e:
        result["web_error"] = f"{type(e).__name__}: {e}"

    try:
        state = shell_json(
            "from evennia.accounts.models import AccountDB; from evennia.utils.search import search_object; "
            "acc=AccountDB.objects.get(username='Timmy'); char=list(acc.characters)[0]; rooms=['Gate','Courtyard','Workshop','Archive','Chapel']; "
            "import json; print(json.dumps({'timmy_home': getattr(char.home,'key',None), 'rooms': {name: bool(search_object(name, exact=True)) for name in rooms}}))"
        )
        result.update(state)
    except Exception as e:
        result["world_error"] = f"{type(e).__name__}: {e}"

    try:
        result["telnet_roundtrip_excerpt"] = telnet_roundtrip()
    except Exception as e:
        result["telnet_error"] = f"{type(e).__name__}: {e}"

    print(json.dumps(result, indent=2))


if __name__ == "__main__":
    main()
