import tempfile

import pytest
from birds.models import (
    Bird,
    BirdSightingEntry,
    BirdSightingLogData,
    BirdingLocation,
)
from django.contrib.auth import get_user_model
from scrobbles.models import Scrobble

User = get_user_model()


@pytest.fixture
def user(db):
    return User.objects.create(email="birder@example.com")


@pytest.fixture
def bird(db):
    return Bird.objects.create(
        common_name="Northern Cardinal",
        scientific_name="Cardinalis cardinalis",
    )


@pytest.fixture
def birding_location(db):
    return BirdingLocation.objects.create(title="Test Park")


@pytest.fixture
def birding_csv_content():
    return """Species,Count,Location,Observation Type,Observation Date,Start Time,Duration,Distance,Area,Party Size,Complete Checklist,# of species,Details
Canada Goose,6,Test Park,Stationary,"May 10, 2026",4:15 PM,9 minute(s),,,4,true,4 species,
Northern Cardinal,2,Test Park,Stationary,"May 10, 2026",4:15 PM,9 minute(s),,,4,true,4 species,At the feeder
"""


@pytest.fixture
def birding_csv_file(birding_csv_content):
    with tempfile.NamedTemporaryFile(
        mode="w", suffix=".csv", delete=False, encoding="utf-8"
    ) as f:
        f.write(birding_csv_content)
        return f.name


@pytest.fixture
def scrobble_with_sightings(user, birding_location, bird):
    return Scrobble.objects.create(
        user=user,
        birding_location=birding_location,
        media_type=Scrobble.MediaType.BIRDING_LOCATION,
        timestamp="2026-05-10 16:15:00+00:00",
        played_to_completion=True,
        log={
            "birds": [
                BirdSightingEntry(
                    bird_id=bird.id, quantity=2, sighting_notes="At the feeder"
                ).asdict
            ],
            "duration_minutes": 9,
            "observation_type": "Stationary",
            "party_size": 4,
            "complete_checklist": True,
        },
    )
