from services.pchome_backfill_status import (
    PchomeBackfillAlreadyRunning,
    fail_pchome_backfill_run,
    finish_pchome_backfill_run,
    get_pchome_backfill_status,
    start_pchome_backfill_run,
    update_pchome_backfill_run,
)


def test_pchome_backfill_status_tracks_running_and_completion(tmp_path, monkeypatch):
    monkeypatch.setenv("PCHOME_BACKFILL_STATUS_PATH", str(tmp_path / "status.json"))

    run = start_pchome_backfill_run(limit=12, operator="tester")
    running = get_pchome_backfill_status()

    assert running["running"] is True
    assert running["status"] == "running"
    assert running["current_run"]["run_id"] == run["run_id"]
    assert running["current_run"]["limit"] == 12

    try:
        start_pchome_backfill_run(limit=5)
    except PchomeBackfillAlreadyRunning as exc:
        assert exc.status["running"] is True
    else:
        raise AssertionError("expected active PChome backfill guard")

    update_pchome_backfill_run(
        run["run_id"],
        stage="matching",
        result={"total_skus": 12, "matched": 3},
    )
    finish_pchome_backfill_run(
        run["run_id"],
        result={"total_skus": 12, "matched": 3},
        pick_result={"written": 9},
    )
    completed = get_pchome_backfill_status()

    assert completed["running"] is False
    assert completed["status"] == "completed"
    assert completed["last_result"]["matched"] == 3
    assert completed["recent_runs"][0]["pick_result"]["written"] == 9


def test_pchome_backfill_status_records_failure(tmp_path, monkeypatch):
    monkeypatch.setenv("PCHOME_BACKFILL_STATUS_PATH", str(tmp_path / "status.json"))

    run = start_pchome_backfill_run(limit=8)
    fail_pchome_backfill_run(run["run_id"], "crawler timeout")
    failed = get_pchome_backfill_status()

    assert failed["running"] is False
    assert failed["status"] == "failed"
    assert failed["last_error"] == "crawler timeout"
    assert failed["recent_runs"][0]["last_error"] == "crawler timeout"


def test_pchome_backfill_status_supports_stale_refresh_stage(tmp_path, monkeypatch):
    monkeypatch.setenv("PCHOME_BACKFILL_STATUS_PATH", str(tmp_path / "status.json"))

    run = start_pchome_backfill_run(limit=120, operator="tester")
    refreshing = update_pchome_backfill_run(
        run["run_id"],
        stage="refreshing_stale",
        message="正在刷新過期價格",
    )

    assert refreshing["stage"] == "refreshing_stale"
    assert refreshing["stage_label"] == "刷新過期 PChome 價格"
    assert refreshing["progress_pct"] > run["progress_pct"]


def test_pchome_backfill_status_supports_stale_recovery_stage(tmp_path, monkeypatch):
    monkeypatch.setenv("PCHOME_BACKFILL_STATUS_PATH", str(tmp_path / "status.json"))

    run = start_pchome_backfill_run(limit=40, operator="tester")
    recovering = update_pchome_backfill_run(
        run["run_id"],
        stage="recovering_stale",
        message="正在搜尋救援過期 identity",
    )

    assert recovering["stage"] == "recovering_stale"
    assert recovering["stage_label"] == "搜尋救援過期 PChome identity"
    assert recovering["progress_pct"] > run["progress_pct"]
