"""DB 시드 — 경기 6개 + AI 예측(부트스트랩) + crowd baseline.

init_db 직후 호출. 이미 경기가 있으면 건너뛴다(idempotent).
"""
from __future__ import annotations

import logging

from sqlalchemy import select

from .database import SessionLocal
from .models import CrowdStats, Match
from .schedule_data import GROUP_A, lock_at, opens_at, parse_kickoff, TEAMS
from .seed_data import generate_crowd

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


async def seed_if_empty() -> None:
    async with SessionLocal() as db:
        existing = (await db.execute(select(Match.match_id))).scalars().first()
        if existing:
            log.info("seed: matches already present — skip")
            return

        for s in GROUP_A:
            kickoff = parse_kickoff(s.kickoff_iso)
            ta, tb = TEAMS[s.team_a], TEAMS[s.team_b]
            match = Match(
                match_id=s.match_id,
                round_label=s.round_label,
                group="A",
                team_a_name=ta["name"],
                team_a_short=ta["shortName"],
                team_a_code=ta["code"],
                team_a_flag=ta["flag"],
                team_b_name=tb["name"],
                team_b_short=tb["shortName"],
                team_b_code=tb["code"],
                team_b_flag=tb["flag"],
                venue=s.venue,
                hook_text=s.hook_text,
                kickoff_at=kickoff,
                opens_at=opens_at(kickoff),
                lock_at=lock_at(kickoff),
                status="scheduled",
            )
            db.add(match)

            crowd = generate_crowd(s.match_id)
            db.add(
                CrowdStats(
                    match_id=s.match_id,
                    total=crowd["total"],
                    team_a_win=crowd["teamAWin"],
                    draw=crowd["draw"],
                    team_b_win=crowd["teamBWin"],
                )
            )
            # AI 예측은 시드하지 않는다 — 워커가 실 API 로 생성.

        await db.commit()
        log.info("seed: %d matches + crowd seeded (예측 없음 — 워커가 실 API 생성)", len(GROUP_A))
