from __future__ import annotations

import pytest

from youtube_cli_agent.errors import ValidationError
from youtube_cli_agent.models import VideoCandidate
from youtube_cli_agent.tools.metadata_validation import MetadataValidationTool


class FakeMetadataBackend:
    def __init__(self, payload: dict):
        self.payload = payload

    def fetch(self, video_url: str) -> dict:
        return self.payload


def make_candidate() -> VideoCandidate:
    return VideoCandidate(
        rank=1,
        video_id="abc123",
        title="Sample",
        channel="Channel",
        url="https://www.youtube.com/watch?v=abc123",
        duration_seconds=120,
        publish_date="20250101",
        description="desc",
    )


def test_metadata_validation_happy_path() -> None:
    backend = FakeMetadataBackend(
        {
            "id": "abc123",
            "title": "Sample",
            "channel": "Channel",
            "webpage_url": "https://www.youtube.com/watch?v=abc123",
            "upload_date": "20250101",
            "duration": 120,
            "description": "Hello",
        }
    )
    tool = MetadataValidationTool(backend=backend)

    metadata = tool.run(make_candidate())

    assert metadata.publish_date == "2025-01-01"
    assert metadata.duration_seconds == 120


def test_metadata_validation_fails_missing_duration() -> None:
    backend = FakeMetadataBackend(
        {
            "id": "abc123",
            "title": "Sample",
            "channel": "Channel",
            "webpage_url": "https://www.youtube.com/watch?v=abc123",
            "upload_date": "20250101",
            "duration": 0,
            "description": "Hello",
        }
    )
    tool = MetadataValidationTool(backend=backend)

    with pytest.raises(ValidationError) as exc:
        tool.run(make_candidate())

    assert exc.value.code == "INVALID_METADATA"
