"""Read-only Agentverse/uAgents bridge to the canonical Compacitas ledgers.

This process publishes no mission state. It answers discovery queries with
records fetched directly from the canonical Embassy origin. Mutating actions
must be signed by the participant and posted to the canonical endpoint.
"""

from __future__ import annotations

import json
import os
import urllib.error
import urllib.parse
import urllib.request

from uagents import Agent, Context, Model


ORIGIN = os.getenv(
    "COMPACITAS_ORIGIN",
    "https://compacitas-embassy.ben193035.chatgpt.site",
).rstrip("/")
SEED = os.getenv("AGENT_SEED_PHRASE", "").strip()

if not SEED:
    raise RuntimeError("AGENT_SEED_PHRASE is required and must remain operator-controlled")


class RelayQuery(Model):
    stream: str = "missions"
    mission_id: str | None = None


class RelayResponse(Model):
    ok: bool
    canonical_url: str
    record_json: str
    boundary: str


def canonical_url(query: RelayQuery) -> str:
    if query.mission_id:
        safe_id = urllib.parse.quote(query.mission_id, safe="")
        return f"{ORIGIN}/api/relay/missions/{safe_id}"
    if query.stream == "commons":
        return f"{ORIGIN}/api/vault"
    return f"{ORIGIN}/api/relay"


def retrieve(url: str) -> dict:
    request = urllib.request.Request(
        url,
        headers={"Accept": "application/json", "User-Agent": "Compacitas-Relay-Mesh/0.1"},
    )
    with urllib.request.urlopen(request, timeout=20) as response:
        if response.status != 200:
            raise RuntimeError(f"canonical ledger returned HTTP {response.status}")
        if response.url != url:
            raise RuntimeError("canonical ledger redirects are not accepted")
        payload = response.read(262_145)
        if len(payload) > 262_144:
            raise RuntimeError("canonical ledger response exceeded 256 KiB")
        return json.loads(payload.decode("utf-8"))


agent = Agent(
    name="compacitas_relay_mesh",
    seed=SEED,
    mailbox=True,
    publish_agent_details=True,
)


@agent.on_message(model=RelayQuery)
async def answer_relay_query(ctx: Context, sender: str, query: RelayQuery) -> None:
    url = canonical_url(query)
    try:
        record = retrieve(url)
        response = RelayResponse(
            ok=True,
            canonical_url=url,
            record_json=json.dumps(record, separators=(",", ":"), sort_keys=True),
            boundary=(
                "This Mailbox response mirrors canonical signed state. It proves neither "
                "Agentverse delivery beyond this response nor citizenship, trust, or authority."
            ),
        )
    except (RuntimeError, ValueError, urllib.error.URLError) as error:
        ctx.logger.warning("canonical relay retrieval failed: %s", error)
        response = RelayResponse(
            ok=False,
            canonical_url=url,
            record_json=json.dumps({"error": "CANONICAL_LEDGER_UNAVAILABLE"}),
            boundary="Fail closed: do not substitute cached or bridge-originated mission state.",
        )
    await ctx.send(sender, response)


if __name__ == "__main__":
    agent.run()

