# -*- coding: utf-8 -*-
"""验证 14 个任务的 E/T/L 分阶段调用（FakeDB/FakeAPI，不访问真实接口或数据库）。"""
import logging
import sys
from pathlib import Path
from datetime import datetime, timedelta
from zoneinfo import ZoneInfo

import pytest

PROJECT_ROOT = Path(__file__).resolve().parents[2]
if str(PROJECT_ROOT) not in sys.path:
    sys.path.insert(0, str(PROJECT_ROOT))

from tasks.base_task import TaskContext
from tests.unit.task_test_utils import (
    TASK_SPECS,
    create_test_config,
    get_db_operations,
    FakeAPIClient,
)


def _build_context(store_id: int) -> TaskContext:
    now = datetime.now(ZoneInfo("Asia/Taipei"))
    return TaskContext(
        store_id=store_id,
        window_start=now - timedelta(minutes=30),
        window_end=now,
        window_minutes=30,
        cursor=None,
    )


@pytest.mark.parametrize("spec", TASK_SPECS)
def test_etl_stage_flow(spec, tmp_path):
    """对每个任务，单独调用 transform/load，验证 counts 结构与 FakeDB 写入。"""
    config = create_test_config("ONLINE", tmp_path / "archive", tmp_path / "temp")
    api = FakeAPIClient({spec.endpoint: spec.sample_records})
    logger = logging.getLogger(f"test_{spec.code.lower()}")

    task_cls = spec.task_cls
    with get_db_operations() as db_ops:
        task = task_cls(config, db_ops, api, logger)
        ctx = _build_context(config.get("app.store_id"))

        # 跳过 extract，直接验证 transform + load
        extracted = {"records": spec.sample_records}
        transformed = task.transform(extracted, ctx)
        counts = task.load(transformed, ctx)

        assert set(counts.keys()) == {"fetched", "inserted", "updated", "skipped", "errors"}
        assert counts["fetched"] == len(spec.sample_records)
        assert counts["errors"] == 0

        # FakeDB 记录（upserts/executes）至少有一条
        upserts = getattr(db_ops, "upserts", [])
        executes = getattr(db_ops, "executes", [])
        assert upserts or executes, "expected db operations to be recorded"
