"""CRUD for `crawl_site` (§5.1)."""
from __future__ import annotations

from typing import Any

from sqlalchemy import select
from sqlalchemy.orm import Session

from govcrawler.models import CrawlSite


def get_by_code(session: Session, site_code: str) -> CrawlSite | None:
    return session.scalar(select(CrawlSite).where(CrawlSite.site_code == site_code))


def get_by_id(session: Session, site_id: int) -> CrawlSite | None:
    return session.get(CrawlSite, site_id)


def list_enabled(session: Session) -> list[CrawlSite]:
    return list(
        session.scalars(
            select(CrawlSite).where(CrawlSite.enabled.is_(True)).order_by(CrawlSite.id)
        )
    )


def upsert_by_code(session: Session, site_code: str, **fields: Any) -> CrawlSite:
    """Create-or-update on site_code. Returns the persisted row (not flushed)."""
    row = get_by_code(session, site_code)
    if row is None:
        row = CrawlSite(site_code=site_code, **fields)
        session.add(row)
    else:
        for k, v in fields.items():
            setattr(row, k, v)
    return row


def set_enabled(session: Session, site_code: str, enabled: bool) -> CrawlSite | None:
    row = get_by_code(session, site_code)
    if row is not None:
        row.enabled = enabled
    return row
