"""
OIMRQS Ops sample artifact: one-day backoffice adapter.

Purpose:
- receive one narrow job request;
- run a browser-backed workflow with visible evidence;
- return a structured status that another tool can consume.

Run locally:
    uvicorn adapter:app --reload --port 8787

Example request:
    curl -X POST http://127.0.0.1:8787/run \
      -H "content-type: application/json" \
      -d '{"job_id":"order-1007","target_url":"https://example.com/admin/orders/1007","mode":"dry_run"}'
"""

from __future__ import annotations

from datetime import datetime, timezone
from pathlib import Path
from typing import Literal

from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, HttpUrl
from playwright.async_api import async_playwright


EVIDENCE_DIR = Path("evidence")
EVIDENCE_DIR.mkdir(exist_ok=True)

app = FastAPI(title="OIMRQS Ops Backoffice Adapter")


class AdapterRequest(BaseModel):
    job_id: str
    target_url: HttpUrl
    mode: Literal["dry_run", "apply"] = "dry_run"


class AdapterResult(BaseModel):
    job_id: str
    status: Literal["validated", "needs_access", "failed"]
    mode: str
    screenshot: str | None
    checked_at: str
    notes: list[str]


@app.post("/run", response_model=AdapterResult)
async def run_job(payload: AdapterRequest) -> AdapterResult:
    checked_at = datetime.now(timezone.utc).isoformat()
    screenshot_path = EVIDENCE_DIR / f"{payload.job_id}.png"
    notes: list[str] = []

    if payload.mode == "apply":
        raise HTTPException(
            status_code=409,
            detail="Sample adapter refuses apply mode until contract, access, and acceptance checks are explicit.",
        )

    async with async_playwright() as p:
        browser = await p.chromium.launch(headless=True)
        page = await browser.new_page(viewport={"width": 1365, "height": 900})

        try:
            response = await page.goto(str(payload.target_url), wait_until="domcontentloaded", timeout=20000)
            notes.append(f"page_status={response.status if response else 'unknown'}")
            notes.append(f"title={await page.title()!r}")
            await page.screenshot(path=screenshot_path, full_page=True)
        except Exception as exc:
            notes.append(f"error={type(exc).__name__}: {exc}")
            await browser.close()
            return AdapterResult(
                job_id=payload.job_id,
                status="needs_access",
                mode=payload.mode,
                screenshot=None,
                checked_at=checked_at,
                notes=notes,
            )

        await browser.close()

    return AdapterResult(
        job_id=payload.job_id,
        status="validated",
        mode=payload.mode,
        screenshot=str(screenshot_path),
        checked_at=checked_at,
        notes=notes,
    )
