"""A bounded evidence-gathering swarm. Python 3.9+, standard library for offline mode.

python3 harbor_swarm.py --mode swarm
python3 harbor_swarm.py --mode solo --fault missing
Optional: install openai, set OPENAI_API_KEY, then add --openai-model MODEL_ID.
Only the public toy pier names, questions, and toy observations enter a live request.
"""
import argparse
import asyncio
import json
from dataclasses import asdict, dataclass

NOTICES = {"north": "Tide rising at 17:00", "east": "Ferry leaves at 17:15", "west": "Ramp open until 18:00"}


@dataclass(frozen=True)
class Task:
    pier: str
    question: str


@dataclass(frozen=True)
class Slip:
    pier: str
    fact: str
    source: str


async def read_notice(task, requested_pier, missing):
    if requested_pier != task.pier:
        raise ValueError("The worker can read only its assigned pier.")
    await asyncio.sleep(0.01)
    if missing and requested_pier == "east":
        raise LookupError("East Pier has no current notice.")
    return Slip(task.pier, NOTICES[task.pier], "town-board/" + task.pier)


async def worker(task, missing, client=None, model=None):
    # The offline policy chooses the same benign tool deterministically.
    if client is None:
        return await read_notice(task, task.pier, missing)
    schema = {"type": "function", "name": "read_notice",
              "description": "Read the current toy notice for your assigned pier.",
              "parameters": {"type": "object", "properties": {"pier": {"type": "string", "enum": [task.pier]}},
                             "required": ["pier"], "additionalProperties": False}, "strict": True}
    instructions = "You are a town scout. Use read_notice once for your assigned pier, then answer from its observation."
    first = await client.responses.create(model=model, instructions=instructions, input=task.question,
                                          tools=[schema], tool_choice={"type": "function", "name": "read_notice"},
                                          parallel_tool_calls=False)
    calls = [item for item in first.output if item.type == "function_call"]
    if len(calls) != 1 or calls[0].name != "read_notice":
        raise ValueError("Worker must request exactly one allowed observation.")
    call = calls[0]
    slip = await read_notice(task, json.loads(call.arguments)["pier"], missing)
    # The next turn sees the actual observation. The reducer trusts the tool receipt.
    await client.responses.create(model=model, previous_response_id=first.id, instructions=instructions,
                                  input=[{"type":"function_call_output", "call_id":call.call_id,
                                          "output":json.dumps(asdict(slip))}], tools=[schema], tool_choice="none")
    return slip


def join(tasks, slips):
    by_pier = {s.pier: s for s in slips}
    if len(by_pier) != len(slips) or set(by_pier) != {t.pier for t in tasks}:
        raise ValueError("The owner needs one unique slip from every assigned pier.")
    for pier, slip in by_pier.items():
        if slip.source != "town-board/" + pier or slip.fact != NOTICES[pier]:
            raise ValueError("The grader could not verify a returned slip against its source.")
    return [asdict(by_pier[t.pier]) for t in tasks]


async def dispatch(mode, missing, seconds, client=None, model=None):
    tasks = [Task(pier, "Read the current public notice at " + pier + " pier.") for pier in NOTICES]
    async def collect():
        if mode != "swarm":
            slips = []
            for job in tasks:
                slips.append(await worker(job, missing, client, model))
            return slips
        handles = [asyncio.create_task(worker(job, missing, client, model)) for job in tasks]
        try:
            return await asyncio.gather(*handles)
        finally:
            for handle in handles:
                if not handle.done():
                    handle.cancel()
            await asyncio.gather(*handles, return_exceptions=True)
    slips = await asyncio.wait_for(collect(), timeout=seconds)
    return {"owner": "Michi", "approach": mode, "bulletin": join(tasks, slips)}


async def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--mode", choices=["solo", "swarm"], default="swarm")
    parser.add_argument("--fault", choices=["none", "missing"], default="none")
    parser.add_argument("--deadline", type=float, default=10)
    parser.add_argument("--openai-model", help="Opt in to billed API calls using this tool-capable model")
    args = parser.parse_args()
    client = None
    if args.openai_model:
        try:
            from openai import AsyncOpenAI
        except ImportError as exc:
            raise SystemExit("Install the openai Python package for live model mode.") from exc
        client = AsyncOpenAI(max_retries=0)
    try:
        report = await dispatch(args.mode, args.fault == "missing", args.deadline, client, args.openai_model)
    except (asyncio.TimeoutError, LookupError, ValueError) as exc:
        raise SystemExit("Bulletin withheld: " + (str(exc) or "crew deadline reached")) from exc
    finally:
        if client is not None:
            await client.close()
    print(json.dumps(report, indent=2))


if __name__ == "__main__":
    asyncio.run(main())
