"""Boot-time seeding of the known recurring saved views (M8).

`seed_default_saved_views` (services/saved_views) is idempotent code —
NOT migration data — so it re-asserts rian's recurring views after any
rebuild-from-legacy rehearsal that TRUNCATEs the user graph. This module
is the async boot wrapper: fired as a background task from the app
lifespan, it never blocks startup and never crashes the app.

It can also be run directly against the sidecar:  python -m scripts.seed_views
"""

from __future__ import annotations

import asyncio
import logging

from sqlalchemy.orm import Session

from app.config import settings
from app.db import get_engine
from app.services.saved_views import seed_default_saved_views

log = logging.getLogger("with.seed")


def _seed_once() -> int:
    with Session(get_engine()) as session:
        return seed_default_saved_views(session)


async def seed_views_on_boot() -> None:
    """Best-effort: seed the default views if the DB is reachable and the
    named users exist. Absent users / transient DB errors are logged and
    swallowed — the seed simply re-runs next boot."""
    if not settings.with_db_url:
        return
    try:
        inserted = await asyncio.to_thread(_seed_once)
        if inserted:
            log.info("seeded %d default saved view(s)", inserted)
    except Exception:
        log.exception("saved-view seed failed — will retry next boot")


def main() -> int:
    logging.basicConfig(level=logging.INFO)
    inserted = _seed_once()
    log.info("seeded %d default saved view(s)", inserted)
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
