"""Host模式：从 stdin 读一行一 JSON，执行任务并 stdout 回一行 JSON。"""

from __future__ import annotations

import asyncio
import json
import os
import sys
from typing import Any

from aicd.host_dispatch import dispatch_host_request, host_err
from aicd.runtime import RuntimeContext


def _state_dir(ctx: RuntimeContext) -> Any:
    return ctx.layout.get("plugins_state")


async def run_host_stdio_loop(ctx: RuntimeContext) -> None:
    """从 stdin 读行；写入 stdout；要求 UTF-8 文本。"""

    require_nonce = os.environ.get("AICD_HOST_REQUIRE_NONCE") == "1"
    state_dir = _state_dir(ctx)
    loop = asyncio.get_event_loop()
    for _stream in (sys.stdout, sys.stderr):
        try:
            _stream.reconfigure(encoding="utf-8", errors="replace")  # type: ignore[attr-defined]
        except (AttributeError, OSError, ValueError):
            pass

    while True:
        line = await loop.run_in_executor(None, sys.stdin.readline)
        if not line:
            break
        line = line.strip()
        if not line:
            continue
        try:
            req = json.loads(line)
        except json.JSONDecodeError as e:
            msg = json.dumps(
                host_err(None, f"invalid json: {e}", code="parse"),
                ensure_ascii=False,
            )
            sys.stdout.write(msg + "\n")
            sys.stdout.flush()
            continue
        if not isinstance(req, dict):
            msg = json.dumps(host_err(None, "request must be object"), ensure_ascii=False)
            sys.stdout.write(msg + "\n")
            sys.stdout.flush()
            continue
        try:
            resp = await dispatch_host_request(
                ctx,
                req,
                state_dir=state_dir,
                require_nonce=require_nonce,
            )
        except Exception as e:  # noqa: BLE001
            resp = host_err(req.get("id"), repr(e), code="internal")
        sys.stdout.write(json.dumps(resp, ensure_ascii=False) + "\n")
        sys.stdout.flush()
