"""
Melaya EXCOM coding session — the native coding loop host.
==========================================================

The runner (excomCoding.ts) spawns this script inside the session worktree
when the engine is "native" (any runner model: Claude Code, Codex, GitHub
Copilot, Ollama, LM Studio). It reads ONE JSON config on stdin:

    {"worktree", "prompt", "goal", "runbookText", "provider", "model",
     "maxTurns", "wallSeconds", "rules"}

runs melayaAgents shared.coding.loop.run_coding_loop() with the executive's
own runner model, and prints `MELCODE {json}` lines (progress / tool /
command / blocked / done). Exit code 0 when the loop finished, 1 otherwise.
The runner stages the shared/ tree and sets PYTHONPATH exactly like the
assistant host (assistantHost.py), so `shared.*` and `agentscope` resolve.
"""
from __future__ import annotations

import json
import os
import sys


def main() -> int:
    raw = sys.stdin.read()
    try:
        cfg = json.loads(raw or "{}")
    except Exception:
        print("MELCODE " + json.dumps({"kind": "done", "ok": False, "summary": "", "commands": 0, "stop": "error",
                                        "error": "the session config could not be read"}), flush=True)
        return 1
    worktree = str(cfg.get("worktree") or "")
    if worktree and os.path.isdir(worktree):
        os.chdir(worktree)
    try:
        from shared.coding.loop import run_coding_loop
    except Exception as e:  # a shared bundle without the coding loop
        print("MELCODE " + json.dumps({"kind": "done", "ok": False, "summary": "", "commands": 0, "stop": "error",
                                        "error": f"the native coding loop is not in this runtime bundle ({e})"}), flush=True)
        return 1
    out = run_coding_loop(cfg, env=dict(os.environ))
    return 0 if out.get("ok") else 1


if __name__ == "__main__":
    sys.exit(main())
