from datetime import datetime

import pytz

from services.pchome_sales_freshness_policy import (
    CONTRACT_VERSION,
    evaluate_pchome_sales_freshness,
)


TAIPEI_TZ = pytz.timezone("Asia/Taipei")


def _taipei(value: str) -> datetime:
    return TAIPEI_TZ.localize(datetime.fromisoformat(value))


def test_two_calendar_days_old_is_ready_before_report_cutoff():
    result = evaluate_pchome_sales_freshness(
        "2026-07-13",
        now=_taipei("2026-07-15T01:05:00"),
    )

    assert result["contract_version"] == CONTRACT_VERSION
    assert result["data_lag_days"] == 2
    assert result["expected_latest_sales_date"] == "2026-07-13"
    assert result["sla_lag_days"] == 0
    assert result["status"] == "grace"
    assert result["grace_period_active"] is True
    assert result["decision_ready"] is True
    assert result["report_due_at"] == "2026-07-15T20:00:00+08:00"


def test_same_snapshot_blocks_after_report_cutoff():
    result = evaluate_pchome_sales_freshness(
        "2026-07-13",
        now=_taipei("2026-07-15T20:01:00"),
    )

    assert result["expected_latest_sales_date"] == "2026-07-14"
    assert result["sla_lag_days"] == 1
    assert result["status"] == "warning"
    assert result["grace_period_active"] is False
    assert result["decision_ready"] is False
    assert result["requires_upstream_acquisition"] is True


def test_previous_day_snapshot_is_ready_after_cutoff():
    result = evaluate_pchome_sales_freshness(
        "2026-07-14",
        now=_taipei("2026-07-15T20:01:00"),
    )

    assert result["sla_lag_days"] == 0
    assert result["status"] == "fresh"
    assert result["decision_ready"] is True


def test_future_snapshot_is_rejected_even_when_it_meets_sla():
    result = evaluate_pchome_sales_freshness(
        "2026-07-16",
        now=_taipei("2026-07-15T10:00:00"),
    )

    assert result["status"] == "future"
    assert result["decision_ready"] is False


def test_missing_and_invalid_snapshots_keep_public_safe_contract():
    missing = evaluate_pchome_sales_freshness(
        None,
        now=_taipei("2026-07-15T10:00:00"),
    )
    invalid = evaluate_pchome_sales_freshness(
        "not-a-date",
        now=_taipei("2026-07-15T10:00:00"),
    )

    assert missing["status"] == "missing"
    assert invalid["status"] == "invalid"
    assert missing["decision_ready"] is False
    assert invalid["decision_ready"] is False
