"""What one address is: `GET /api/pages/status?path=`, the read behind the page-status badge.

Sources of truth: `services/publish.py` (`status_of_path`, the one resolver), `docs/SEO.md`
("Page status: what a signed-in admin sees"), `services/access.py` (the permission
`pages.status`), `tests/test_page_status.py`. The read writes nothing and calls no head
builder; the badge is drawn by the SPA alone, so no served body ever carries it and a crawler
sees the same page as a signed-in owner.
"""

from __future__ import annotations

from dataclasses import asdict

from fastapi import APIRouter, Depends, HTTPException, Query
from pydantic import BaseModel
from sqlalchemy.orm import Session

from app.config import settings
from app.db import get_db
from app.services import publish

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

#: Longer than any address the site mints; a longer one is a probe, not a page.
PATH_MAX = 400


class PageStatusOut(BaseModel):
    path: str
    #: One of `publish.STATUSES`: indexable, noindex, unlisted, hidden, or missing.
    status: str
    reason: str
    #: The robots directive the head sends, or None when it sends none.
    robots: str | None = None
    in_sitemap: bool
    #: Where a `hidden` address sends its visitor.
    forwards_to: str | None = None
    #: The address the page is really at.
    canonical: str | None = None
    #: False while the site is members-only, when every response carries
    #: `X-Robots-Tag: noindex, nofollow` and the word says what the page WOULD be once it flips.
    site_open: bool


@router.get("/status", response_model=PageStatusOut)
def page_status(path: str = Query(min_length=1, max_length=PATH_MAX), db: Session = Depends(get_db)) -> dict:
    if not path.startswith("/"):
        raise HTTPException(status_code=422, detail={"error_code": "BAD_PATH",
                                                     "summary": "A path starts with '/' and names one address."})
    return {**asdict(publish.status_of_path(db, path)), "site_open": settings.site_open}
