from bincio.extract.writer import make_activity_id, build_summary, _slugify
from bincio.extract.metrics import ComputedMetrics
from bincio.extract.models import ParsedActivity, DataPoint
from datetime import datetime, timezone


def _dummy_activity(title=None):
    ts = datetime(2024, 6, 1, 7, 30, 12, tzinfo=timezone.utc)
    return ParsedActivity(
        points=[DataPoint(timestamp=ts)],
        sport="cycling",
        started_at=ts,
        source_file="test.fit",
        source_hash="sha256:abc",
        title=title,
    )


def test_id_with_title():
    act = _dummy_activity("Morning Ride")
    aid = make_activity_id(act)
    assert aid == "2024-06-01T073012Z-morning-ride"


def test_id_without_title():
    act = _dummy_activity()
    aid = make_activity_id(act)
    assert aid == "2024-06-01T073012Z"


def test_slugify():
    assert _slugify("Morning Ride!") == "morning-ride"
    assert _slugify("  Vélo  ") == "velo"   # é → e via NFKD + ASCII
    assert _slugify("") == ""


def test_id_utc_conversion():
    """Non-UTC timestamps should be converted to UTC in the ID."""
    from datetime import timedelta
    tz_plus2 = timezone(timedelta(hours=2))
    ts = datetime(2024, 6, 1, 9, 30, 12, tzinfo=tz_plus2)  # 07:30:12 UTC
    act = ParsedActivity(
        points=[DataPoint(timestamp=ts)],
        sport="cycling",
        started_at=ts,
        source_file="test.fit",
        source_hash="sha256:abc",
    )
    assert make_activity_id(act) == "2024-06-01T073012Z"


def test_build_summary_required_fields():
    """build_summary should include all fields needed by the schema."""
    act = _dummy_activity("Test Ride")
    metrics = ComputedMetrics(
        distance_m=10000.0,
        duration_s=3600,
        moving_time_s=3500,
        elevation_gain_m=100.0,
        elevation_loss_m=95.0,
        avg_speed_kmh=10.0,
        max_speed_kmh=20.0,
        avg_hr_bpm=None,
        max_hr_bpm=None,
        avg_cadence_rpm=None,
        avg_power_w=None,
        max_power_w=None,
        bbox=None,
        start_latlng=None,
        end_latlng=None,
        mmp=None,
        best_efforts=None,
        best_climb_m=None,
    )
    summary = build_summary(act, metrics, "2024-06-01T073012Z-test-ride")
    # Required fields per schema
    assert summary["id"] == "2024-06-01T073012Z-test-ride"
    assert summary["title"] == "Test Ride"
    assert summary["sport"] == "cycling"
    assert "started_at" in summary
    assert "privacy" in summary
    assert "detail_url" in summary
    assert "track_url" in summary
