"""Debug / observability endpoints — view recent activity in a browser."""
from collections import deque
from datetime import datetime, timezone
from typing import Any, Deque, Dict

from fastapi import APIRouter
from fastapi.responses import HTMLResponse

router = APIRouter(prefix="/debug", tags=["debug"])

# In-memory ring buffer of the last N received tank-allocation commands.
_MAX = 100
_recent: Deque[Dict[str, Any]] = deque(maxlen=_MAX)


def record_allocation(payload: Dict[str, Any], event_id: str) -> None:
    _recent.appendleft({
        "received_at": datetime.now(timezone.utc).isoformat(timespec="seconds"),
        "event_id": event_id,
        "payload": payload,
    })


@router.get("/allocations.json")
async def allocations_json() -> dict:
    return {"count": len(_recent), "items": list(_recent)}


@router.get("/allocations", response_class=HTMLResponse)
async def allocations_page() -> str:
    rows = ""
    for item in _recent:
        p = item["payload"]
        meta = p.get("metadata") or {}
        rows += f"""
        <tr>
            <td>{item['received_at']}</td>
            <td>{p.get('job_id','')}</td>
            <td>{p.get('licence_number','')}</td>
            <td>{p.get('tank_id','')}</td>
            <td>{meta.get('j_cust_code','')}</td>
            <td>{'⚠️' if p.get('is_dangerous_goods') else ''}</td>
            <td><code>{item['event_id']}</code></td>
        </tr>"""
    if not rows:
        rows = '<tr><td colspan="7" style="text-align:center;padding:30px;color:#888">No allocations received yet</td></tr>'

    return f"""<!doctype html>
<html><head>
  <meta charset="utf-8">
  <title>BTL FastLane – Recent Allocations</title>
  <meta http-equiv="refresh" content="5">
  <style>
    body {{ font-family: -apple-system, Segoe UI, sans-serif; margin: 20px; background:#f5f5f7; }}
    h1 {{ margin:0 0 10px }}
    .sub {{ color:#666; margin-bottom:20px }}
    table {{ width:100%; border-collapse:collapse; background:#fff; box-shadow:0 1px 3px rgba(0,0,0,.08); }}
    th, td {{ padding:10px 12px; text-align:left; border-bottom:1px solid #eee; font-size:14px; }}
    th {{ background:#0066cc; color:#fff; font-weight:600 }}
    tr:hover td {{ background:#fafafa }}
    code {{ font-size:11px; color:#666 }}
  </style>
</head><body>
  <table>
    <thead>
      <tr>
        <th>Received (UTC)</th>
        <th>Job ID</th>
        <th>Licence</th>
        <th>Tank ID</th>
        <th>Customer</th>
        <th>DG</th>
        <th>Event ID</th>
      </tr>
    </thead>
    <tbody>{rows}</tbody>
  </table>
</body></html>"""
