"""On startup, ensure every feed in default.toml/portfolio.toml has a row in
the `feeds` table. Existing rows are left untouched so admin overrides
(enabled=0 to mute a noisy source) survive restarts."""
from __future__ import annotations

from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession

from app.config import load_feeds, get_settings
from app.models import Feed


async def bootstrap_feeds(session: AsyncSession) -> int:
    s = get_settings()
    declared = load_feeds(s.BASELINE_TOML, s.PORTFOLIO_TOML)
    existing = {
        (f.category, f.name): f
        for f in (await session.execute(select(Feed))).scalars().all()
    }
    inserted = 0
    for category, items in declared.items():
        for name, url in items:
            key = (category, name)
            if key in existing:
                # Refresh URL if it changed in TOML; preserve enabled/failures.
                if existing[key].url != url:
                    existing[key].url = url
                continue
            session.add(Feed(category=category, name=name, url=url))
            inserted += 1
    await session.commit()
    return inserted
