"""Tests for NWSL scraper."""

from datetime import datetime
from unittest.mock import patch

import pytest

from sportstime_parser.scrapers.nwsl import NWSLScraper, create_nwsl_scraper
from sportstime_parser.scrapers.base import RawGameData
from sportstime_parser.tests.fixtures import (
    load_json_fixture,
    NWSL_ESPN_SCOREBOARD_JSON,
)


class TestNWSLScraperInit:
    """Test NWSLScraper initialization."""

    def test_creates_scraper_with_season(self):
        """Test scraper initializes with correct season."""
        scraper = NWSLScraper(season=2026)
        assert scraper.sport == "nwsl"
        assert scraper.season == 2026

    def test_factory_function_creates_scraper(self):
        """Test factory function creates correct scraper."""
        scraper = create_nwsl_scraper(season=2026)
        assert isinstance(scraper, NWSLScraper)
        assert scraper.season == 2026

    def test_expected_game_count(self):
        """Test expected game count is correct for NWSL."""
        scraper = NWSLScraper(season=2026)
        assert scraper.expected_game_count == 182

    def test_sources_in_priority_order(self):
        """Test sources are returned in correct priority order."""
        scraper = NWSLScraper(season=2026)
        sources = scraper._get_sources()
        assert sources == ["espn"]


class TestESPNParsing:
    """Test ESPN API response parsing."""

    def test_parses_completed_games(self):
        """Test parsing completed games from ESPN."""
        scraper = NWSLScraper(season=2026)
        data = load_json_fixture(NWSL_ESPN_SCOREBOARD_JSON)
        games = scraper._parse_espn_response(data, "http://espn.com/api")

        completed = [g for g in games if g.status == "final"]
        assert len(completed) == 2

        # Angel City @ Thorns
        la_por = next(g for g in completed if g.away_team_raw == "Angel City FC")
        assert la_por.home_team_raw == "Portland Thorns FC"
        assert la_por.away_score == 1
        assert la_por.home_score == 2
        assert la_por.stadium_raw == "Providence Park"

    def test_parses_scheduled_games(self):
        """Test parsing scheduled games from ESPN."""
        scraper = NWSLScraper(season=2026)
        data = load_json_fixture(NWSL_ESPN_SCOREBOARD_JSON)
        games = scraper._parse_espn_response(data, "http://espn.com/api")

        scheduled = [g for g in games if g.status == "scheduled"]
        assert len(scheduled) == 1

        sd_bay = scheduled[0]
        assert sd_bay.away_team_raw == "San Diego Wave FC"
        assert sd_bay.home_team_raw == "Bay FC"
        assert sd_bay.stadium_raw == "PayPal Park"

    def test_parses_venue_info(self):
        """Test venue information is extracted."""
        scraper = NWSLScraper(season=2026)
        data = load_json_fixture(NWSL_ESPN_SCOREBOARD_JSON)
        games = scraper._parse_espn_response(data, "http://espn.com/api")

        for game in games:
            assert game.stadium_raw is not None


class TestGameNormalization:
    """Test game normalization and canonical ID generation."""

    def test_normalizes_games_with_canonical_ids(self):
        """Test games are normalized with correct canonical IDs."""
        scraper = NWSLScraper(season=2026)

        raw_games = [
            RawGameData(
                game_date=datetime(2026, 4, 10),
                home_team_raw="Portland Thorns FC",
                away_team_raw="Angel City FC",
                stadium_raw="Providence Park",
                home_score=2,
                away_score=1,
                status="final",
                source_url="http://example.com",
            )
        ]

        games, review_items = scraper._normalize_games(raw_games)

        assert len(games) == 1
        game = games[0]

        # Check canonical ID format
        assert game.id == "nwsl_2026_anf_por_0410"
        assert game.sport == "nwsl"
        assert game.season == 2026

        # Check team IDs
        assert game.home_team_id == "team_nwsl_por"
        assert game.away_team_id == "team_nwsl_anf"

        # Check scores preserved
        assert game.home_score == 2
        assert game.away_score == 1

    def test_creates_review_items_for_unresolved_teams(self):
        """Test review items are created for unresolved teams."""
        scraper = NWSLScraper(season=2026)

        raw_games = [
            RawGameData(
                game_date=datetime(2026, 4, 10),
                home_team_raw="Unknown Team XYZ",
                away_team_raw="Portland Thorns FC",
                stadium_raw="Providence Park",
                status="scheduled",
            ),
        ]

        games, review_items = scraper._normalize_games(raw_games)

        # Game should not be created due to unresolved team
        assert len(games) == 0

        # But there should be a review item
        assert len(review_items) >= 1


class TestTeamAndStadiumScraping:
    """Test team and stadium data scraping."""

    def test_scrapes_all_nwsl_teams(self):
        """Test all NWSL teams are returned."""
        scraper = NWSLScraper(season=2026)
        teams = scraper.scrape_teams()

        # NWSL has 14 teams
        assert len(teams) == 14

        # Check team IDs are unique
        team_ids = [t.id for t in teams]
        assert len(set(team_ids)) == 14

        # Check all teams have required fields
        for team in teams:
            assert team.id.startswith("team_nwsl_")
            assert team.sport == "nwsl"
            assert team.city
            assert team.name
            assert team.full_name
            assert team.abbreviation

    def test_scrapes_all_nwsl_stadiums(self):
        """Test all NWSL stadiums are returned."""
        scraper = NWSLScraper(season=2026)
        stadiums = scraper.scrape_stadiums()

        # Should have stadiums for all teams
        assert len(stadiums) == 14

        # Check stadium IDs are unique
        stadium_ids = [s.id for s in stadiums]
        assert len(set(stadium_ids)) == 14

        # Check all stadiums have required fields
        for stadium in stadiums:
            assert stadium.id.startswith("stadium_nwsl_")
            assert stadium.sport == "nwsl"
            assert stadium.name
            assert stadium.city
            assert stadium.state
            assert stadium.country == "USA"
            assert stadium.latitude != 0
            assert stadium.longitude != 0


class TestScrapeFallback:
    """Test fallback behavior (NWSL only has ESPN)."""

    def test_returns_failure_when_espn_fails(self):
        """Test scraper returns failure when ESPN fails."""
        scraper = NWSLScraper(season=2026)

        with patch.object(scraper, '_scrape_espn') as mock_espn:
            mock_espn.side_effect = Exception("ESPN failed")

            result = scraper.scrape_games()

            assert not result.success
            assert "All sources failed" in result.error_message


class TestSeasonMonths:
    """Test season month calculation."""

    def test_gets_correct_season_months(self):
        """Test correct months are returned for NWSL season."""
        scraper = NWSLScraper(season=2026)
        months = scraper._get_season_months()

        # NWSL season is March-November
        assert len(months) == 9  # Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov

        # Check first month is March of season year
        assert months[0] == (2026, 3)

        # Check last month is November
        assert months[-1] == (2026, 11)
