"""Tests for get_asset_recent_use_counts and smart-match high-use exclusion."""

import json
import sys
from pathlib import Path
from unittest.mock import MagicMock, patch

import pytest

ROOT = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(ROOT / "apps" / "api"))
sys.path.insert(0, str(ROOT / "packages"))


class TestGetAssetRecentUseCounts:
    """Test asset_segment_tracker.get_asset_recent_use_counts."""

    def _make_asset_model(self, asset_id, used_time_ranges=None):
        from packages.adapters.sqlalchemy_impl.models import AssetModel

        model = AssetModel(
            id=asset_id,
            name=f"asset-{asset_id}",
            file_type="video",
            status="ready",
            asset_library_id="lib1",
            project_id="proj1",
            file_size=1000,
            file_url=f"https://example.com/{asset_id}.mp4",
            uploaded_by_user_id="user1",
        )
        model.classification_result = json.dumps(
            {
                "used_time_ranges": used_time_ranges or [],
            }
        )
        return model

    def test_empty_asset_ids_returns_empty(self):
        from app.services.asset_segment_tracker import get_asset_recent_use_counts

        db = MagicMock()
        result = get_asset_recent_use_counts(db, [])
        assert result == {}

    def test_no_usage_returns_zero(self):
        from app.services.asset_segment_tracker import get_asset_recent_use_counts

        db = MagicMock()
        model = self._make_asset_model("a1", [])
        db.query.return_value.filter.return_value.all.return_value = [model]

        result = get_asset_recent_use_counts(db, ["a1"])
        assert result == {"a1": 0}

    def test_counts_distinct_plan_ids(self):
        from app.services.asset_segment_tracker import get_asset_recent_use_counts

        db = MagicMock()
        ranges = [
            {"start": 0, "end": 5, "plan_id": "plan1", "created_at": "2026-08-01T00:00:00"},
            {"start": 5, "end": 10, "plan_id": "plan1", "created_at": "2026-08-01T00:01:00"},
            {"start": 0, "end": 5, "plan_id": "plan2", "created_at": "2026-08-02T00:00:00"},
            {"start": 0, "end": 5, "plan_id": "plan3", "created_at": "2026-08-03T00:00:00"},
        ]
        model = self._make_asset_model("a1", ranges)
        db.query.return_value.filter.return_value.all.return_value = [model]

        result = get_asset_recent_use_counts(db, ["a1"])
        assert result == {"a1": 3}

    def test_limits_to_recent_n(self):
        from app.services.asset_segment_tracker import get_asset_recent_use_counts

        db = MagicMock()
        ranges = [
            {"start": 0, "end": 5, "plan_id": f"plan{i}", "created_at": f"2026-08-{i+1:02d}T00:00:00"}
            for i in range(10)
        ]
        model = self._make_asset_model("a1", ranges)
        db.query.return_value.filter.return_value.all.return_value = [model]

        result = get_asset_recent_use_counts(db, ["a1"], recent_video_count=5)
        assert result["a1"] == 5

    def test_missing_asset_defaults_to_zero(self):
        from app.services.asset_segment_tracker import get_asset_recent_use_counts

        db = MagicMock()
        db.query.return_value.filter.return_value.all.return_value = []

        result = get_asset_recent_use_counts(db, ["missing_asset"])
        assert result == {"missing_asset": 0}
