"""Test backlog operations."""

import json
import os
import tempfile
from pathlib import Path
import pytest

from state.backlog import load_backlog, save_backlog, get_lead, add_lead, update_lead, get_leads_by_status
from state.schema import validate_lead


@pytest.fixture
def temp_backlog():
    """Create temporary backlog file for testing."""
    fd, temp_path = tempfile.mkstemp(suffix='.json')
    os.environ['ABSEL_BACKLOG_PATH'] = temp_path
    
    yield temp_path
    
    if os.path.exists(temp_path):
        os.unlink(temp_path)
    if 'ABSEL_BACKLOG_PATH' in os.environ:
        del os.environ['ABSEL_BACKLOG_PATH']


def test_load_empty_backlog(temp_backlog):
    """Load should return empty list when file doesn't exist."""
    result = load_backlog()
    assert result == []


def test_save_and_load_backlog(temp_backlog):
    """Save and load should work atomically."""
    test_data = [
        {"id": "1", "name": "Test Lead 1", "lead_status": "active"},
        {"id": "2", "name": "Test Lead 2", "lead_status": "imported_legacy"},
    ]
    
    save_backlog(test_data)
    
    loaded = load_backlog()
    assert len(loaded) == 2
    assert loaded[0]["id"] == "1"
    assert loaded[1]["id"] == "2"


def test_get_lead(temp_backlog):
    """Get lead by ID should return correct lead."""
    test_data = [
        {"id": "lead-123", "name": "Test Lead", "lead_status": "active"},
    ]
    save_backlog(test_data)
    
    lead = get_lead("lead-123")
    assert lead is not None
    assert lead["name"] == "Test Lead"
    
    lead = get_lead("nonexistent")
    assert lead is None


def test_get_leads_by_status(temp_backlog):
    """Get leads by status should filter correctly."""
    test_data = [
        {"id": "1", "name": "Active Lead", "lead_status": "active"},
        {"id": "2", "name": "Legacy Lead", "lead_status": "imported_legacy"},
        {"id": "3", "name": "Another Active", "lead_status": "active"},
    ]
    save_backlog(test_data)
    
    active = get_leads_by_status("active")
    assert len(active) == 2
    
    legacy = get_leads_by_status("imported_legacy")
    assert len(legacy) == 1


def test_add_lead_valid(temp_backlog):
    """Add lead should validate and append."""
    lead = {
        "id": "new-lead",
        "name": "New Business LLC",
        "email": "test@newbusiness.com",
        "lead_status": "active",
        "filing_date": "2026-05-19",
        "harvested_at": "2026-05-20T00:00:00Z",
        "harvest_source": "ct_sos",
        "temporal_category": "fresh",
    }
    
    add_lead(lead)
    
    loaded = load_backlog()
    assert len(loaded) == 1
    assert loaded[0]["id"] == "new-lead"


def test_add_lead_invalid(temp_backlog):
    """Add lead should reject invalid leads."""
    lead = {
        "id": "bad-lead",
        "name": "",  # Invalid - empty name
    }
    
    with pytest.raises(ValueError):
        add_lead(lead)


def test_update_lead(temp_backlog):
    """Update lead should modify fields atomically."""
    test_data = [
        {
            "id": "update-test",
            "name": "Original Name",
            "lead_status": "active",
            "email": "original@test.com",
            "filing_date": "2026-05-19",
            "harvested_at": "2026-05-20T00:00:00Z",
            "harvest_source": "ct_sos",
            "temporal_category": "fresh",
        }
    ]
    save_backlog(test_data)
    
    update_lead("update-test", {
        "name": "Updated Name",
        "score": 85,
        "last_updated": "2026-05-20T12:00:00Z",
    })
    
    lead = get_lead("update-test")
    assert lead["name"] == "Updated Name"
    assert lead["score"] == 85
    assert lead["email"] == "original@test.com"  # Unchanged


def test_update_nonexistent_lead(temp_backlog):
    """Update should raise KeyError for nonexistent lead."""
    with pytest.raises(KeyError):
        update_lead("nonexistent", {"name": "Test"})


def test_atomic_write(temp_backlog):
    """Save should use atomic write (temp file + rename)."""
    test_data = [{"id": "1", "name": "Test", "lead_status": "active"}]
    
    save_backlog(test_data)
    
    with open(temp_backlog, 'r') as f:
        content = f.read()
        assert "Test" in content
    
    loaded = load_backlog()
    assert len(loaded) == 1