"""Reusable orchestrator harness for plan runners.

Every runner script in ``scripts/`` opens a Matrix client, logs in, optionally
invites an observer user to auto-created rooms, builds an ``Orchestrator``,
runs a project, and prints a summary. That boilerplate is ~80 lines of mostly
identical setup. This module factors it out so a plan runner (and the
plan-builder runner) don't have to duplicate it.

The harness does not hold any CLI-parsing or per-project task authoring —
callers pass the ``(agents, tasks, staged_tasks)`` triple that
:func:`agora.plan.loader.instantiate_plan` produces.
"""

from __future__ import annotations

import asyncio
import contextlib
import sys
import warnings
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any

from agora.core.agent import AgentConfig
from agora.core.errors import AgoraError
from agora.core.task import Task
from agora.fleet.llm_adapter import create_llm_adapter
from agora.fleet.orchestrator import Orchestrator, ProjectResult
from agora.fleet.profiles import ModelProfile, build_llm_factory, resolve_base_url
from agora.fleet.vram import check_model_fits, raise_if_wont_fit
from agora.matrix.client import AgoraMatrixClient, MatrixClientProtocol, NullMatrixClient
from agora.matrix.room_manager import RoomManager


@dataclass
class HarnessConfig:
    """Everything a plan runner needs to stand up an Orchestrator.

    The config-shaped fields (endpoints + credentials) are REQUIRED (owner ruling
    2B.2 / Q3): their only default lives in :class:`agora.config.Settings`. Build
    one with :meth:`from_settings` — the single Settings->HarnessConfig mapping
    point. This module reads no env and never imports ``agora.config``.
    """

    # Required — endpoints + credentials, injected from Settings.
    homeserver: str
    system_password: str
    observer_user: str
    ollama_base_url: str
    # Identity with stable non-secret defaults.
    server_name: str = "agora.local"
    system_user: str = "@agora:agora.local"
    # Dataclass default only for hand-built configs; from_settings() always
    # overrides it from Settings.review_timeout_seconds (the single source).
    review_timeout_seconds: float = 300.0
    max_parallel_agents: int = 2
    max_task_retries: int = 2
    work_dir: Path = field(default_factory=lambda: Path("workspace"))
    knowledge_cache_dir: Path | None = None
    enable_observer: bool = True
    enable_web_fetch: bool = False
    fetch_max_text_bytes: int = 65_536
    auto_hooks_enabled: bool = True
    skip_vram_check: bool = False
    # Opt-in for plan-authoring tools (plan_upsert_agent, plan_add_task_spec,
    # plan_finalize). The plan-builder runner sets this True; run_plan.py and
    # other executors leave it False so emitted plans don't expose the
    # meta-authoring surface to their agents.
    plan_authoring_enabled: bool = False
    # v2.5: how many times the router may re-dispatch an upstream task because
    # a downstream test failed with an ImportError pointing at one of its
    # files. Separate from ``max_task_retries`` so routed retries don't
    # compete for the owning task's normal retry pool.
    routed_retry_budget: int = 2
    # v3 harness-reliability (findings F1). ``tool_errors="corrective"`` renders
    # tool validation/handler failures as a CorrectiveError (schema + hint)
    # instead of leaking a raw crash string; "raw" is v2 behaviour byte-for-byte.
    # ``nudge_budget`` caps in-loop completion nudges (0 = off = v2 behaviour).
    # ``review_budget`` caps in-loop completion reviews (S6, v8): on a valid
    # mark_complete the harness reads the written output back to the model and
    # asks it to confirm or revise (0 = off, byte-identical to v3.2).
    tool_errors: str = "raw"
    nudge_budget: int = 0
    review_budget: int = 0
    # S7 (run 2.4): reasoning-salvage nudges. On a turn with 0 tool calls, empty
    # stripped content, and a non-empty thinking trace, re-prompt ONCE carrying
    # the model's own draft verbatim + "emit the tool call now". 0 (default) =
    # off = construct-nothing = byte-identical to pre-S7.
    salvage_budget: int = 0

    @classmethod
    def from_settings(cls, settings: Any, work_dir: str | Path = "workspace") -> HarnessConfig:
        """Build from a Settings-like object (the composition root passes
        ``agora.config.get_settings()``). Duck-typed on purpose: this module imports
        neither ``os`` nor ``agora.config`` — env is read only in config.py. Campaign
        params override the behavioural knobs downstream (2B.iii precedence)."""
        tool_errors = (settings.harness_tool_errors or "raw").strip() or "raw"
        if tool_errors not in ("raw", "corrective"):
            raise ValueError(
                f"harness_tool_errors={tool_errors!r} invalid; expected 'raw' or 'corrective'"
            )
        work_dir_path = Path(work_dir)
        return cls(
            homeserver=settings.matrix_homeserver,
            system_password=settings.matrix_password,
            observer_user=settings.observer_user,
            ollama_base_url=settings.ollama_base_url,
            server_name=settings.matrix_server_name,
            system_user=settings.matrix_user_id,
            review_timeout_seconds=settings.review_timeout_seconds,
            max_parallel_agents=settings.max_parallel_agents,
            max_task_retries=settings.max_task_retries,
            routed_retry_budget=settings.routed_retry_budget,
            tool_errors=tool_errors,
            nudge_budget=settings.harness_nudge_budget,
            review_budget=settings.harness_review_budget,
            salvage_budget=settings.harness_salvage_budget,
            enable_web_fetch=settings.enable_web_fetch,
            skip_vram_check=settings.skip_vram_check,
            work_dir=work_dir_path,
            knowledge_cache_dir=work_dir_path / ".knowledge",
        )


async def preflight_vram(
    model: str,
    base_url: str,
    safety_margin_mib: int = 512,
    *,
    skip: bool = False,
) -> None:
    """Best-effort VRAM check + warm-up gate. Prints the reason line, raises on hard fail.

    ``skip`` (the composition root passes ``Settings.skip_vram_check``) bypasses the
    check entirely — the escape hatch for when the pre-flight is wrong and you know
    it. This is the policy layer; the math in :mod:`agora.fleet.vram` is unaware of it.

    Skipped for non-Ollama models — there's no local GPU memory to budget against
    (Ollama is the only backend today, so this is effectively always active).

    ``safety_margin_mib`` is sourced from ``profile.vram.safety_margin_mib``
    in the standard call path. The estimation formula itself is unchanged
    (see :func:`agora.fleet.vram.check_model_fits`).
    """
    if skip:
        print(f"[*] VRAM check skipped for {model} (skip_vram_check set)")
        return
    if not model.startswith("ollama/"):
        print(f"[*] VRAM check skipped for {model} (remote provider)")
        return
    print(f"[*] VRAM check for {model}...")
    check = await check_model_fits(model, base_url=base_url, safety_margin_mib=safety_margin_mib)
    print(f"  {check.reason}")
    raise_if_wont_fit(check, model)


async def build_matrix_client(cfg: HarnessConfig) -> MatrixClientProtocol:
    """Log in as the system user and wire the auto-invite shim if observer is set.

    With ``enable_observer=False`` this returns a :class:`NullMatrixClient` and
    never touches the network: an unobserved run has no reason to require a
    homeserver, a password, or rooms nobody opens. Provenance is unaffected —
    JSONL + run.log are written unconditionally (F3); only the live room view
    goes away. That makes Python + Ollama the whole dependency set for a phased
    run, with Conduit an opt-in observation surface.
    """
    if not cfg.enable_observer:
        print(
            "[*] Matrix surface OFF (enable_observer=False) — no Conduit required.\n"
            "    Provenance is unaffected: run.log + JSONL are written as always;\n"
            "    only the live room view is absent. Set enable_observer=True to watch."
        )
        return NullMatrixClient(homeserver=cfg.homeserver, user_id=cfg.system_user)

    # Loud, clear failure when the system agent has no Matrix password — better
    # than an opaque auth error from Conduit. (harness stays config-free per the
    # composition-root allowlist, so the message is inlined rather than imported.)
    if not cfg.system_password:
        raise AgoraError(
            "required secret AGORA_MATRIX_PASSWORD is not set (the system agent "
            "has no Matrix password). Copy .env.example to .env and set it, or "
            "export AGORA_MATRIX_PASSWORD. See .env.example for the local-dev value."
        )
    print(f"[*] Logging into Conduit as {cfg.system_user}")
    client = AgoraMatrixClient(homeserver=cfg.homeserver, user_id=cfg.system_user)
    # Bound the login. An unreachable homeserver must produce a fast, named
    # failure — never an open-ended await. (2026-07-15: a dead Conduit hung
    # run_phased here for minutes with zero output and no CPU, looking for all
    # the world like a model stall; the runner's preflight checked Ollama but
    # not Conduit, so nothing caught it earlier. agora.doctor.check_conduit has
    # carried this same bound since the integration-hardening pass — this is the
    # library path catching up.)
    try:
        await asyncio.wait_for(client.login(cfg.system_password), timeout=8.0)
    except TimeoutError as exc:
        # Close the half-open session before surfacing, or every timeout leaks an
        # aiohttp connector ("Unclosed client session").
        with contextlib.suppress(Exception):
            await client.close()
        raise AgoraError(
            f"Matrix login timed out after 8s against {cfg.homeserver} "
            f"(as {cfg.system_user}). Is Conduit up? "
            f"`cd conduit && docker compose up -d`, then `agora doctor`."
        ) from exc

    if cfg.observer_user:
        _orig_create_room = client.create_room

        async def _create_with_observer(name, topic="", invite=None, initial_state=None):
            merged = list(invite or [])
            if cfg.observer_user not in merged:
                merged.append(cfg.observer_user)
            return await _orig_create_room(
                name=name, topic=topic, invite=merged, initial_state=initial_state
            )

        client.create_room = _create_with_observer  # type: ignore[assignment]
        print(f"[*] Auto-inviting {cfg.observer_user} to every created room")

    return client


def build_orchestrator(
    cfg: HarnessConfig,
    client: AgoraMatrixClient,
    model: str,
    *,
    profile: ModelProfile | None = None,
    observer: Any = None,
    llm_factory: Any = None,
) -> Orchestrator:
    """Construct an :class:`Orchestrator` with sensible defaults for plan runners.

    When ``profile`` is supplied, the LLM factory is built via
    :func:`build_llm_factory` so all inference params (num_ctx, max_tokens,
    keep_alive, base_url, num_parallel) flow from the profile. When it's
    None, the legacy env-driven closure is kept verbatim for back-compat.

    ``llm_factory`` overrides the factory entirely (e.g. a strategy-wrapped one
    from a runner). When None the factory is built as described above — the
    default path is unchanged.
    """
    room_manager = RoomManager(client, homeserver_name=cfg.server_name)

    # A very short review timeout with the interactive observer enabled will
    # auto-reject a project before a human can respond — fine for headless
    # sweeps (which set it deliberately), confusing anywhere a person is
    # watching. Warn so an interactive user notices the misconfiguration.
    if cfg.enable_observer and cfg.review_timeout_seconds < 10:
        warnings.warn(
            f"review_timeout_seconds={cfg.review_timeout_seconds}s with the "
            "observer enabled will auto-reject before a human can review; "
            "intended only for headless runs.",
            stacklevel=2,
        )

    if profile is not None:
        # The profile's Ollama endpoint is an optional override; None inherits
        # the injected Settings endpoint (cfg.ollama_base_url). Resolve once so
        # the factory and warmup pin the same daemon.
        ollama_base_url = resolve_base_url(profile, cfg.ollama_base_url)
        built_factory = build_llm_factory(profile, ollama_base_url)
        keep_alive = profile.keep_alive
    else:
        ollama_base_url = cfg.ollama_base_url
        keep_alive = "30m"

        def built_factory(model_ref: str):
            # Empty model → fall back to the harness default. v2.3 plan-builder
            # emits agents with ``model=""`` (the model can't reliably guess a
            # valid model id); the harness owns the runtime model choice anyway.
            if not model_ref:
                model_ref = model
            # Build adapter kwargs. Ollama is the only backend; it needs our base_url.
            kwargs: dict[str, Any] = {"timeout_seconds": 600.0}
            if model_ref.startswith("ollama/"):
                kwargs["base_url"] = cfg.ollama_base_url
            return create_llm_adapter(model_ref, **kwargs)

    # Caller-supplied factory (e.g. a strategy-wrapped one) wins; else use the
    # one built above. None ⇒ default path, unchanged.
    if llm_factory is None:
        llm_factory = built_factory

    cfg.work_dir.mkdir(parents=True, exist_ok=True)
    if cfg.knowledge_cache_dir is not None:
        cfg.knowledge_cache_dir.mkdir(parents=True, exist_ok=True)

    return Orchestrator(
        matrix_client=client,
        room_manager=room_manager,
        llm_factory=llm_factory,
        work_dir=str(cfg.work_dir),
        homeserver_name=cfg.server_name,
        max_parallel_agents=cfg.max_parallel_agents,
        enable_observer=cfg.enable_observer,
        repo_root=str(cfg.work_dir),
        knowledge_cache_dir=(str(cfg.knowledge_cache_dir) if cfg.knowledge_cache_dir else None),
        ollama_base_url=ollama_base_url,
        skip_warmup=False,
        warmup_deadline=600.0,
        keep_alive=keep_alive,
        review_timeout_seconds=cfg.review_timeout_seconds,
        enable_web_fetch=cfg.enable_web_fetch,
        fetch_timeout_seconds=30.0,
        fetch_max_bytes=1_048_576,
        fetch_max_text_bytes=cfg.fetch_max_text_bytes,
        auto_hooks_enabled=cfg.auto_hooks_enabled,
        plan_authoring_enabled=cfg.plan_authoring_enabled,
        routed_retry_budget=cfg.routed_retry_budget,
        tool_errors=cfg.tool_errors,
        nudge_budget=cfg.nudge_budget,
        review_budget=cfg.review_budget,
        salvage_budget=cfg.salvage_budget,
        observer=observer,
    )


def seed_workspace(flow: Any, project_name: str, work_dir_root: Path) -> None:
    """Write framework-owned shared files into the executor's project work_dir.

    v2.6+ plans embed free-form context (``brief``, ``api_spec``) directly in
    the YAML. The executor runs in a fresh per-project work_dir that doesn't
    have those files yet — scaffolders + LLM stages expect them present at
    well-known paths (``plan/brief.md``, ``plan/api_spec.md``). This helper
    seeds them ONCE at kickoff from ``flow.brief`` / ``flow.api_spec``.

    v2.7: also pre-writes ``src/*.py`` STUB files from ``api_spec``. Each
    stub has the matching class/function signatures + ``raise
    NotImplementedError`` bodies. This means:

      - ``py_compiles`` + ``file_exists`` postconditions on src/ files pass
        trivially at kickoff (the stub is valid python).
      - Contract tests can use REAL module-level imports (``from src.foo
        import Bar``) because the file exists — no more "deferred imports"
        needed. Collection never fails on ``ImportError``.
      - The implementer's job collapses to "replace NotImplementedError
        with real body" via the existing ``add_class_method`` /
        ``add_function`` upsert-by-name tools (Sprint 7.4).
      - Tester + implementer physically CANNOT disagree on API — the stub
        file is the single framework-owned source of truth.

    Safe to call even when both fields are empty (no-op). Never overwrites
    an existing file — if the executor workspace is being re-used (rerun
    after partial failure), the on-disk copy wins.
    """
    from agora.plan.api_spec import parse_api_spec, render_impl_stub

    project_dir = work_dir_root / project_name
    plan_dir = project_dir / "plan"
    plan_dir.mkdir(parents=True, exist_ok=True)
    brief = getattr(flow, "brief", "") or ""
    if brief:
        brief_path = plan_dir / "brief.md"
        if not brief_path.exists():
            brief_path.write_text(brief, encoding="utf-8")
    api_spec_text = getattr(flow, "api_spec", "") or ""
    if not api_spec_text:
        return
    spec_path = plan_dir / "api_spec.md"
    if not spec_path.exists():
        spec_path.write_text(api_spec_text, encoding="utf-8")

    modules = parse_api_spec(api_spec_text)
    for module in modules:
        stub_rel = module.path.replace("\\", "/")
        # v2.7(c): only stub PRODUCTION modules. If the spec wrongly
        # included a test file path (``tests/test_X.py`` or
        # ``src/tests/X.py``), skip it — tests get scaffolded separately
        # by the test-authoring pipeline (Sprint 7.2-7.3).
        if stub_rel.startswith("tests/") or stub_rel.startswith("src/tests/"):
            continue
        if not stub_rel.startswith("src/") or not stub_rel.endswith(".py"):
            continue
        stub_path = project_dir / stub_rel
        if stub_path.exists() and stub_path.stat().st_size > 0:
            continue  # respect prior run's partial state
        stub_path.parent.mkdir(parents=True, exist_ok=True)
        stub_path.write_text(render_impl_stub(module), encoding="utf-8")
    # Also drop an `__init__.py` into the common src/ package root so the
    # module path ``src.foo`` resolves without the caller wiring it.
    src_root = project_dir / "src"
    if src_root.is_dir():
        init_path = src_root / "__init__.py"
        if not init_path.exists():
            init_path.write_text("", encoding="utf-8")


async def run_plan_project(
    cfg: HarnessConfig,
    project_name: str,
    agents: list[AgentConfig],
    tasks: list[Task],
    staged_tasks: dict[str, Any] | None = None,
    model_hint: str | None = None,
    max_loopbacks: int = 2,
) -> ProjectResult:
    """End-to-end: preflight → login → orchestrate → run → close client.

    ``model_hint`` is used for the VRAM preflight; falls back to the first
    agent's model (runners usually use a single model). Returns the
    :class:`ProjectResult` and prints a one-line summary per task.
    """
    model = model_hint or (agents[0].model if agents else "ollama/qwen2.5:7b-instruct")
    await preflight_vram(model, cfg.ollama_base_url, skip=cfg.skip_vram_check)

    client = await build_matrix_client(cfg)
    try:
        orchestrator = build_orchestrator(cfg, client, model)
        print(f"[*] Running project '{project_name}' (observer={cfg.enable_observer})")
        print(f"   review_timeout_seconds={cfg.review_timeout_seconds}")
        print(f"   max_task_retries={cfg.max_task_retries}")
        print()
        result = await orchestrator.run_project(
            project_name,
            agents,
            tasks,
            max_loopbacks=max_loopbacks,
            staged_tasks=staged_tasks,
            max_task_retries=cfg.max_task_retries,
        )
    finally:
        await client.close()

    _print_summary(result)
    return result


def _print_summary(result: ProjectResult) -> None:
    print("\n" + "=" * 72)
    print(f"Project phase: {result.project.phase.value}")
    print(f"Success: {result.success}")
    print(f"Project room: {result.project_room_id}")
    print(f"Duration: {result.duration_seconds:.1f}s")
    print(
        f"Tokens: in={int(result.total_tokens.get('input_tokens', 0))}, "
        f"out={int(result.total_tokens.get('output_tokens', 0))}"
    )
    # Per-run USD cost only appears if a metered backend sets cost_usd; the
    # Ollama adapter does not.
    cost = result.total_tokens.get("cost_usd", 0.0)
    if cost:
        # Sub-cent values still useful for cross-provider comparison.
        print(f"Cost:   ${float(cost):.4f} USD")
    for r in result.task_results:
        mark = "OK" if r.success else "FAIL"
        print(f"  [{mark}] {r.task_id}: {r.iterations} iter  -> {r.output[:80]}")


def force_utf8_stdio() -> None:
    """Windows cp1252 cannot encode many characters LLMs produce. Force UTF-8.

    Call from a runner's top-level before any logging is configured.

    ``line_buffering=True`` is load-bearing. A bare ``TextIOWrapper`` is
    BLOCK-buffered whenever stdout is a pipe or a file, so a redirected run
    emits nothing until the process exits — and it silently defeats ``python
    -u``, because that flag configures the *original* stdout, not the wrapper
    installed over it. Without this, `run_phased … --auto > run.txt` shows an
    empty file for the whole run and is indistinguishable from a hang
    (observed 2026-07-15: multi-minute runs written off as dead purely because
    nothing streamed). Progress output is a diagnostic surface; buffering it
    away costs real debugging time.
    """
    import io

    if sys.stdout.encoding and sys.stdout.encoding.lower() != "utf-8":
        sys.stdout = io.TextIOWrapper(
            sys.stdout.buffer, encoding="utf-8", errors="replace", line_buffering=True
        )
        sys.stderr = io.TextIOWrapper(
            sys.stderr.buffer, encoding="utf-8", errors="replace", line_buffering=True
        )


__all__ = [
    "HarnessConfig",
    "build_matrix_client",
    "build_orchestrator",
    "force_utf8_stdio",
    "preflight_vram",
    "run_plan_project",
]
