"""手动维护任务：回填需求池记录的 video_list / video_count。"""
from __future__ import annotations

import logging
from typing import Any

from supply_infra.db.repositories.multi_demand_pool_di_repo import MultiDemandPoolDiRepository
from supply_infra.db.session import get_session
from supply_infra.odps.client import get_odps_client
from supply_infra.scheduler.jobs.sync_multi_demand_pool_odps_to_mysql import _to_mysql_rows

logger = logging.getLogger(__name__)


def backfill_video_list(partition_date: str) -> dict[str, Any]:
    """从 ODPS 回填指定分区的 video_list / video_count（每条最多前 10 个 video_id）。"""
    logger.info("Backfill video_list for partition: %s", partition_date)
    raw_rows = get_odps_client().fetch_multi_demand_pool(partition_date)
    mysql_rows = _to_mysql_rows(raw_rows, partition_date)

    with get_session() as session:
        updated = MultiDemandPoolDiRepository(session).update_video_fields(
            partition_date,
            mysql_rows,
        )

    result = {
        "partition_date": partition_date,
        "fetched": len(raw_rows),
        "unique_rows": len(mysql_rows),
        "updated": updated,
        "with_video": sum(1 for row in mysql_rows if row.get("video_list")),
    }
    logger.info("Backfill video_list completed: %s", result)
    return result
