"""Event log helpers: who did what.

The frontend logs users in and sends the username in the ``X-Username`` header on every data-changing call.
The backend trusts that value (it is not authentication; ``X-API-Key`` stays the gate) and records every such
action in the ``event_log`` table, written here and read by ``GET /ocr/events``.

Use ``Username`` as a parameter type on a data-changing route, and wrap the work in ``record``:

    with events.record(user, "MERGE_RUN", code) as ev:
        out = do_the_work()
        ev.details["series"] = 12

``record`` writes a STARTED row first, then SUCCEEDED / FAILED / CANCELLED, and always re-raises, so responses
do not change. A background job creates its row at submit time (``start``) and the worker finishes it
(``record(..., event_id=...)``).
"""

import logging
from contextlib import contextmanager
from typing import Annotated, Any, Dict, Optional

from fastapi import Depends, Header, HTTPException

from . import database

logger = logging.getLogger("ocr.events")

USERNAME_MAX_LENGTH = 64


def require_username(x_username: Annotated[Optional[str], Header(description="Logged-in user of the frontend")] = None) -> str:
    """FastAPI dependency: the ``X-Username`` header, 1-64 printable characters; 400 when missing or invalid."""
    name = (x_username or "").strip()
    if not name or len(name) > USERNAME_MAX_LENGTH or not name.isprintable():
        raise HTTPException(status_code=400, detail="X-Username header is required (1-64 printable characters)")
    return name


Username = Annotated[str, Depends(require_username)]


class Event:
    """The open event of a ``record`` block: extend ``details``, or set the target once it is known."""

    def __init__(self, event_id: int):
        self.id = event_id
        self.details: Dict[str, Any] = {}
        self.target_type: Optional[str] = None
        self.target_id: Optional[Any] = None

    def target(self, target_type: str, target_id: Any) -> None:
        self.target_type, self.target_id = target_type, target_id


def start(user: str, action: str, instrument_code: Optional[str] = None, fiscal_year: Optional[str] = None,
          target_type: Optional[str] = None, target_id: Optional[Any] = None,
          details: Optional[Dict[str, Any]] = None) -> int:
    """Writes a STARTED event and returns its id."""
    return database.add_event(user, action, instrument_code, fiscal_year, target_type, target_id, details=details)


@contextmanager
def record(user: str, action: str, instrument_code: Optional[str] = None, fiscal_year: Optional[str] = None,
           target_type: Optional[str] = None, target_id: Optional[Any] = None,
           details: Optional[Dict[str, Any]] = None, event_id: Optional[int] = None, keep_open: bool = False):
    """Records one action: STARTED when the block begins, then SUCCEEDED, FAILED (error and status_code in the
    details) or CANCELLED (merge_service.MergeCancelled). Always re-raises. With event_id the row made by ``start``
    is finished instead of a new one being written. keep_open=True leaves the row STARTED when the block succeeds
    (a background job finishes it later) but still closes it as FAILED / CANCELLED on an error."""
    from .services import merge_service      # local: services import this package's database

    ev = Event(event_id if event_id is not None else start(user, action, instrument_code, fiscal_year,
                                                           target_type, target_id, details))
    if event_id is not None and details:
        ev.details.update(details)      # merged into the stored details on finish
    try:
        yield ev
    except merge_service.MergeCancelled:
        _finish(ev, "CANCELLED")
        raise
    except HTTPException as exc:
        ev.details.update(error=str(exc.detail), status_code=exc.status_code)
        _finish(ev, "FAILED")
        raise
    except Exception as exc:
        ev.details.update(error=f"{type(exc).__name__}", status_code=500)
        _finish(ev, "FAILED")
        raise
    else:
        if not keep_open:
            _finish(ev, "SUCCEEDED")


def _finish(ev: Event, status: str) -> None:
    try:
        database.finish_event(ev.id, status, ev.details, ev.target_type, ev.target_id)
    except Exception:       # the log must never break the action it records
        logger.exception("Could not finish event %s (%s)", ev.id, status)
