"""The Gemini half of the harness.

The harness is TypeScript; the Antigravity SDK is Python with a compiled runtime binary, so this
runs as a child process and speaks JSON Lines over stdin/stdout. It is deliberately thin: it owns
no policy and makes no decisions. Every tool call is referred back to Node over localhost, so
gitGuard, secretGuard and the Jev gate keep ONE implementation rather than being rewritten here
and drifting from the originals.

  Node → here   {"type":"run","brief":...,"cwd":...,"resume":...,"model":...,"guard_url":...}
                {"type":"steer","text":...}
                {"type":"stop"}
  here → Node   {"type":"event","kind":"text"|"tool"|"todo"|"usage"|"done"|"ready", ...}
                {"type":"fatal","message":...}

The event names are the harness's own `AgentEvent` union, not Antigravity's, because that union
was written for its consumers and already has no vendor in it.
"""
import asyncio
import json
import os
import sys
import urllib.request

from contextlib import AsyncExitStack

from google.antigravity import Agent, LocalAgentConfig
from google.antigravity.hooks import policy, post_tool_call, pre_tool_call_decide
from google.antigravity.types import HookResult, McpStreamableHttpServer

GUARD_URL = ""


def emit_spend(agent, model: str) -> None:
    try:
        u = agent.conversation.total_usage
    except Exception:  # noqa: BLE001 — no conversation, nothing was billed
        return
    if not (u.total_token_count or 0):
        return
    # The runtime's prompt count leaves OUT what came from cache — the two are separate buckets
    # (measured 16 Oct: 40k prompt + 93k cached over four calls, total_token_count = prompt +
    # output + thinking). FlareDeck prices "prompt" as ALL input with "cached" a part of it, the
    # Gemini API's own meaning, so they are added here; sent as they came, spend read ~6x low.
    uncached = u.prompt_token_count or 0
    cached = u.cached_content_token_count or 0
    emit({"type": "event", "kind": "spend", "model": str(model or "unknown"),
          "prompt": uncached + cached, "cached": cached,
          "output": u.candidates_token_count or 0, "thinking": u.thoughts_token_count or 0})


def emit(obj: dict) -> None:
    """One JSON object per line, flushed — Node is reading this as a stream, not a file."""
    sys.stdout.write(json.dumps(obj) + "\n")
    sys.stdout.flush()


def ask_node(path: str, payload: dict) -> dict:
    """Put the decision where the policy already lives. A guard that cannot be reached DENIES:
    an agent that keeps working because its supervisor is unreachable is the failure this
    harness exists to prevent."""
    try:
        req = urllib.request.Request(
            f"{GUARD_URL}{path}",
            data=json.dumps(payload).encode(),
            headers={"Content-Type": "application/json"},
        )
        with urllib.request.urlopen(req, timeout=120) as r:
            return json.loads(r.read().decode())
    except Exception as e:  # noqa: BLE001 - any failure here must be closed, not loud
        return {"allow": False, "message": f"The harness could not be reached to approve this ({e})."}


@pre_tool_call_decide
async def gate(data):
    """Antigravity's shell tool is `run_command` and its argument is `CommandLine` — NOT
    `command`. Reading the wrong key yields an empty string, which every guard would wave
    through, so the name is asserted rather than assumed."""
    args = dict(getattr(data, "args", {}) or {})
    verdict = ask_node("/tool-call", {
        "name": str(getattr(data, "name", "")),
        # Which server a tool came from: the harness pre-approves FlareDeck's READ tools the same
        # way it does for the other engine, and cannot tell them apart without this.
        "server": str(getattr(data, "server_name", "") or ""),
        "args": args,
    })
    if not verdict.get("allow", False):
        # Either key. The harness grew a second set of guards that answer with `reason` while
        # this read only `message`, so every one of them reached the model as the bare words
        # "Refused by the harness." — no which-checkout, no use-push_branch, no the-card-is-not-
        # finished. An agent that is told no and not told why cannot correct; it argues, or goes
        # looking. Reading both means a new guard cannot be silent by picking the other word.
        why = verdict.get("reason") or verdict.get("message")
        return HookResult(
            allow=False,
            message=str(why) if why else (
                "The harness refused this and gave no reason, which is a bug in the harness. "
                "Do not retry it unchanged; say on the card what you were trying to do."
            ),
        )
    modified = verdict.get("modified_args")
    if modified:
        return HookResult(allow=True, modified_args=modified)
    return HookResult(allow=True)


@post_tool_call
async def seen(data):
    """PostToolCallHook is an InspectHook: it can SEE a result and cannot change it. So this
    reports a secret that came back rather than redacting it — the harness decides what to do
    about an engine that cannot redact, and says so out loud rather than pretending."""
    result = getattr(data, "result", None)
    if result is not None:
        ask_node("/tool-result", {"name": str(getattr(data, "name", "")), "result": str(result)[:20000]})
    return None


# What a flush is worth saying on its own. Model text arrives in small pieces; one harness event
# per piece would be a pane of fragments, and one event for the whole turn — which is what
# `response.text()` gave — is a blank pane for minutes and then a wall.
FLUSH_CHARS = 280

# How long the model may say NOTHING before the turn is abandoned. It streams text, thinking and
# tool calls, so a silence this long is a stalled stream rather than a long thought: HR-0622 sat
# eleven minutes with an open connection to Google, zero CPU, and no chunk — and nothing noticed,
# because the harness only ever waited. An unattended agent cannot wait forever.
STALL_SECONDS = float(os.environ.get("FLAREDECK_AGENT_STALL_SECONDS", "300"))


async def stdin_lines() -> asyncio.StreamReader:
    """
    stdin as an async stream.

    Deliberately not `run_in_executor(sys.stdin.readline)`: that parks a thread in the default
    executor, which `asyncio.run` waits for at shutdown — and since the harness holds the pipe open
    for the life of the process, the read never returns and the sidecar hangs on exit instead of
    dying. This also means ONE reader owns the fd, so the run message and any steer come off the
    same stream and nothing is lost to buffering.
    """
    loop = asyncio.get_running_loop()
    # 16 MB a line, not asyncio's 64 KB default: the first line carries the brief and the system
    # instructions, which include the project's CLAUDE.md — HR Goat's is 83 KB, and every turn
    # failed "Separator is found, but chunk is longer than limit" until this was raised.
    reader = asyncio.StreamReader(limit=16 * 1024 * 1024)
    await loop.connect_read_pipe(lambda: asyncio.StreamReaderProtocol(reader), sys.stdin)
    return reader


async def _steers(queue: "asyncio.Queue[str]", lines: asyncio.StreamReader) -> None:
    """
    Lines the harness sends while a turn is running. stdin was read once, for the run message, and
    then never again, so anything typed into the pane had nowhere to go.
    """
    while True:
        raw = await lines.readline()
        if not raw:
            return
        try:
            msg = json.loads(raw.decode())
        except Exception:  # noqa: BLE001
            continue
        if msg.get("type") == "steer" and msg.get("text"):
            await queue.put(str(msg["text"]))


async def _drain(response, said: list[str]) -> None:
    """
    One turn's chunk stream, mapped onto harness events as it arrives.

    `response.text()` waits for everything and returns a single string, which is why a Gemini turn
    showed nothing at all until it was over. The same response exposes the semantic stream; this
    reads that instead, so text, thinking and tool calls appear while they happen.
    """
    buffer: list[str] = []

    def flush() -> None:
        joined = "".join(buffer).strip()
        buffer.clear()
        if joined:
            said.append(joined)
            emit({"type": "event", "kind": "text", "text": joined})

    # `chunks` is a PROPERTY returning a fresh cursor, not a method. Calling it raises
    # "'async_generator' object is not callable" — which a hand-written fake that defines it as a
    # method will never show you. Iterated by hand rather than with `async for`, so that every
    # chunk has a deadline and a stalled stream ends the turn instead of hanging it.
    cursor = response.chunks.__aiter__()
    while True:
        try:
            chunk = await asyncio.wait_for(cursor.__anext__(), timeout=STALL_SECONDS)
        except StopAsyncIteration:
            break
        except asyncio.TimeoutError:
            emit({"type": "event", "kind": "tool",
                  "name": f"no output from the model for {int(STALL_SECONDS // 60)}m — abandoning this turn"})
            try:
                response.cancel()
            except Exception:  # noqa: BLE001
                pass
            break

        kind = type(chunk).__name__
        if kind == "Text":
            buffer.append(chunk.text)
            # On a paragraph break, or once it has said enough to be worth reading.
            if "\n\n" in chunk.text or sum(len(x) for x in buffer) >= FLUSH_CHARS:
                flush()
        elif kind == "Thought":
            # Its reasoning, one line of it: enough to tell a thinking agent from a stuck one
            # without turning the pane into a transcript of everything it considered.
            first_line = (chunk.text or "").strip().splitlines()
            if first_line:
                emit({"type": "event", "kind": "tool", "name": f"thinking · {first_line[0][:110]}"})
        elif kind == "ToolCall":
            name = str(getattr(chunk, "name", "") or "")
            args = getattr(chunk, "args", None) or {}
            if name == "run_command":
                # The SDK has used more than one name for this; rather than guess, take the first
                # string that looks like a command. A bare "run_command" in the pane says nothing.
                command = ""
                for key in ("CommandLine", "command", "Command", "cmd", "script"):
                    if str(args.get(key, "") or "").strip():
                        command = str(args[key]).strip()
                        break
                if not command:
                    # Last resort, and it must not pick the WORKING DIRECTORY, which is the
                    # longest string in these args and told you nothing: the pane read
                    # "run_command · /Users/…/agent-xgv0osv9…" for every shell call.
                    guesses = [
                        v.strip() for k, v in args.items()
                        if isinstance(v, str) and v.strip()
                        and k.lower() not in ("cwd", "workingdirectory", "working_dir", "dir", "path")
                        and not v.strip().startswith("/")
                    ]
                    command = max(guesses, key=len) if guesses else ""
                if command:
                    name = f"run_command · {command[:120]}"
            server = str(getattr(chunk, "server_name", "") or "")
            emit({"type": "event", "kind": "tool", "name": f"{server + ': ' if server else ''}{name}"})
        elif kind == "ToolResult":
            error = getattr(chunk, "error", None)
            if error:
                emit({"type": "event", "kind": "tool",
                      "name": f"{getattr(chunk, 'name', 'tool')} failed · {str(error)[:140]}"})
    flush()


async def run_turn(agent, brief: str, lines: asyncio.StreamReader) -> str:
    """
    Run a turn, streaming it, and let the harness interrupt it.

    A steer cancels the response in flight and sends what was typed as the next message. The
    conversation keeps its history, so the model sees what it had already done and carries on from
    there rather than starting over.
    """
    queue: "asyncio.Queue[str]" = asyncio.Queue()
    reader = asyncio.create_task(_steers(queue, lines))
    said: list[str] = []
    prompt = brief
    try:
        while True:
            response = await agent.chat(prompt)
            drain = asyncio.create_task(_drain(response, said))
            steer = asyncio.create_task(queue.get())
            done, _ = await asyncio.wait({drain, steer}, return_when=asyncio.FIRST_COMPLETED)

            if drain in done:
                steer.cancel()
                drain.result()  # re-raise anything the stream failed with
                # Something typed while the turn was finishing is the next turn, not lost input.
                if not queue.empty():
                    prompt = queue.get_nowait()
                    emit({"type": "event", "kind": "tool", "name": "picking up what you typed"})
                    continue
                return "\n\n".join(said).strip()

            prompt = steer.result()
            emit({"type": "event", "kind": "tool", "name": "interrupted — taking what you typed"})
            response.cancel()
            drain.cancel()
            try:
                await drain
            except asyncio.CancelledError:
                pass
    finally:
        reader.cancel()


async def main() -> None:
    global GUARD_URL
    lines = await stdin_lines()
    first = json.loads((await lines.readline()).decode())
    if first.get("type") != "run":
        emit({"type": "fatal", "message": f"expected a run message, got {first.get('type')!r}"})
        return
    GUARD_URL = first["guard_url"]

    kwargs = {
        "system_instructions": first.get("system_instructions") or "",
        "policies": [policy.allow_all()],   # the gate above is the policy; this just defers to it
        "hooks": [gate, seen],
        # What it may CHANGE, which is not always where it starts: a turn with no card reads the
        # shared checkout and writes only to scratch space.
        "workspaces": first.get("workspaces") or [first["cwd"]],
    }
    # FlareDeck, reached over HTTP with the HARNESS's own token — so the model's tools act as the
    # same account the harness listens as. Two identities for one agent is a thing that has gone
    # wrong here before and is hard to see once it has.
    mcp = [
        McpStreamableHttpServer(name=m["name"], url=m["url"], headers=m.get("headers") or {})
        for m in (first.get("mcp") or [])
    ]
    if mcp:
        kwargs["mcp_servers"] = mcp
    if os.environ.get("GOOGLE_GENAI_USE_VERTEXAI"):
        kwargs.update(vertex=True, project=os.environ["GOOGLE_CLOUD_PROJECT"],
                      location=os.environ.get("GOOGLE_CLOUD_LOCATION", "us-central1"))
    else:
        kwargs["api_key"] = os.environ["GEMINI_API_KEY"]
    if first.get("model"):
        kwargs["model"] = first["model"]
    # Helpers, as the SDK's own sub-agents (flaredeck-agent helpers.ts). Minimal mode: the default
    # cost ~$0.70 for two searches in testing, minimal ~$0.05. Skipped, never fatal, if this SDK
    # build lacks a field — a missing helper must not be the reason a card fails.
    if first.get("subagents"):
        try:
            from google.antigravity.types import AgentBehavior, SubagentCapabilities, SubagentConfig
            kwargs["subagents"] = [
                SubagentConfig(
                    name=s["name"], description=s["description"],
                    system_instructions=s.get("system_instructions") or "",
                    model=s.get("model"),
                    capabilities=SubagentCapabilities(agent_behavior=AgentBehavior.MINIMAL),
                )
                for s in first["subagents"]
            ]
        except Exception as e:  # noqa: BLE001
            emit({"type": "event", "kind": "tool", "name": f"helpers not available ({type(e).__name__}: {e})"})

    # How hard it thinks. The option rides on the Gemini endpoint, which means naming the model as
    # a ModelTarget rather than a bare string — so this is attempted and then abandoned quietly if
    # the SDK disagrees: a tuning knob must never be the reason a card fails. Vertex is left alone
    # because its endpoint is a different type and nothing here has exercised it.
    level = first.get("thinking_level")
    if level and kwargs.get("model") and not kwargs.get("vertex"):
        try:
            from google.antigravity.types import (
                GeminiAPIEndpoint, GeminiModelOptions, ModelTarget, ModelType, ThinkingLevel,
            )
            kwargs["model"] = ModelTarget(
                name=str(kwargs["model"]),
                types=[ModelType.TEXT],
                endpoint=GeminiAPIEndpoint(
                    api_key=kwargs.get("api_key"),
                    options=GeminiModelOptions(thinking_level=ThinkingLevel(level)),
                ),
            )
        except Exception as e:  # noqa: BLE001
            emit({"type": "event", "kind": "tool",
                  "name": f"thinking level {level} not applied ({type(e).__name__}) — running at the default"})
    if first.get("resume"):
        kwargs["conversation_id"] = first["resume"]

    # A conversation lives in the Antigravity runtime, which dies with this process — so a session
    # id the harness stored before a restart names something that no longer exists, and asking for
    # it fails the whole card: "Failed to create agent: conversation ... not found". The card is
    # not lost by that. Its whole thread is on FlareDeck and it is perfectly workable from a fresh
    # conversation, so an unusable resume is dropped rather than raised.
    #
    # Both the construction AND the entering are covered, because the runtime is only reached on
    # entry — that is where the failure actually surfaces.
    stack = AsyncExitStack()
    try:
        agent = await stack.enter_async_context(Agent(LocalAgentConfig(**kwargs)))
    except Exception as e:  # noqa: BLE001
        if not kwargs.get("conversation_id") or "not found" not in str(e).lower():
            raise
        gone = str(kwargs.pop("conversation_id"))[:8]
        await stack.aclose()
        # Said out loud: an agent that silently forgot a conversation would re-read the card and
        # quietly redo work it had already reported.
        emit({"type": "event", "kind": "text",
              "text": f"The earlier session for this card is gone ({gone}…), so this starts fresh from the card and its comments."})
        stack = AsyncExitStack()
        agent = await stack.enter_async_context(Agent(LocalAgentConfig(**kwargs)))

    async with stack:
        # "connected", not "configured", and it is not a guess: a server that fails to load raises
        # during Agent construction ("MCP load failed for flaredeck: ..."), so reaching this line
        # means every server in `mcp` is really attached to THIS session. The harness refuses to
        # work a card otherwise, and it is right to — the tool names come from the harness's own
        # discovery a moment earlier, because the SDK gives no way to enumerate a session's tools.
        emit({"type": "event", "kind": "ready", "tools": first.get("tool_names") or [],
              "mcp": [{"name": m.name, "status": "connected"} for m in mcp],
              "apiKeySource": "vertex" if kwargs.get("vertex") else "gemini-api-key",
              "permissionMode": "harness-gated",
              "sessionId": str(getattr(agent, "conversation_id", "") or "")})
        try:
            text = await run_turn(agent, first["brief"], lines)
        finally:
            # Every token this run used, whether it finished or not — a failed turn is billed too.
            # The harness turns it into dollars and checks the workspace's Gemini spend limit.
            emit_spend(agent, first.get("model") or "")
        # The session id only exists AFTER the first turn — conversation_id is None until then —
        # so the ready event above could never carry it, and the harness, finding no session,
        # skipped the handover entirely: "no session to write a handover from". That handover is
        # where an agent writes its notes and closes the card, so the work half ran and the
        # report half silently never did. Sending ready again with the real id is enough: the
        # harness stores a session id from any ready that has one.
        session_id = str(getattr(agent, "conversation_id", "") or "")
        if session_id:
            emit({"type": "event", "kind": "ready", "tools": first.get("tool_names") or [],
                  "mcp": [{"name": m.name, "status": "connected"} for m in mcp],
                  "apiKeySource": "vertex" if kwargs.get("vertex") else "gemini-api-key",
                  "permissionMode": "harness-gated", "sessionId": session_id})
        emit({"type": "event", "kind": "done", "ok": True, "result": text or ""})


if __name__ == "__main__":
    try:
        asyncio.run(main())
    except Exception as e:  # noqa: BLE001
        emit({"type": "fatal", "message": str(e)})
        sys.exit(1)
