"""Test full orchestration pipeline with mocked services."""

import pytest
import os
import tempfile
from unittest.mock import patch, MagicMock
from capabilities.orchestration import run_pipeline


@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 mock_harvest_recent(days):
    """Mock harvest that returns sample result."""
    from capabilities.harvest import HarvestResult
    
    result = HarvestResult()
    result.total_fetched = 5
    result.total_kept = 5
    result.total_new = 5
    
    return result


def test_pipeline_runs_with_mocks(temp_backlog):
    """Test that pipeline runs end-to-end with mocked services."""
    from state.backlog import add_lead
    
    sample_leads = [
        {
            "id": f"lead-{i}",
            "name": f"Test Business {i} LLC",
            "city": "Hartford",
            "state": "CT",
            "email": f"test{i}@business.com",
            "filing_date": "2026-05-19",
            "naics": "541110 - Offices of Lawyers",
            "entity_type": "LLC",
            "citizenship": "Domestic",
            "lead_status": "active",
            "harvested_at": "2026-05-20T00:00:00Z",
            "harvest_source": "ct_sos",
            "temporal_category": "fresh",
        }
        for i in range(3)
    ]
    
    for lead in sample_leads:
        add_lead(lead)
    
    def mock_call_llm(prompt, **kwargs):
        response = f"""ANCHOR: Test anchor.

SUBJECT: Test Subject for Lead

This is a test email body. It should be around 90-120 words.
We help businesses with their document workflows.
Let me know if you have questions.

Mark Mazza
Inside Sales
ABS | Xerox
www.xeroxne.com"""
        return response, {"model_used": "test-model"}
    
    with patch('capabilities.orchestration.harvest_recent', side_effect=mock_harvest_recent):
        with patch('capabilities.drafting.call_llm', side_effect=mock_call_llm):
            brief = run_pipeline(days=1, limit=2, draft=True)
    
    assert "Morning Brief" in brief
    assert "Test Business" in brief
    assert len(brief) > 100


def test_pipeline_json_output(temp_backlog):
    """Test pipeline JSON output format."""
    from state.backlog import add_lead
    
    lead = {
        "id": "json-test-lead",
        "name": "JSON Test LLC",
        "city": "New Haven",
        "state": "CT",
        "email": "test@json.com",
        "filing_date": "2026-05-19",
        "naics": "541110",
        "entity_type": "LLC",
        "citizenship": "Domestic",
        "lead_status": "active",
        "harvested_at": "2026-05-20T00:00:00Z",
        "harvest_source": "ct_sos",
        "temporal_category": "fresh",
    }
    add_lead(lead)
    
    def mock_harvest(days):
        from capabilities.harvest import HarvestResult
        result = HarvestResult()
        result.total_fetched = 1
        result.total_kept = 1
        return result
    
    with patch('capabilities.orchestration.harvest_recent', side_effect=mock_harvest):
        brief = run_pipeline(days=1, limit=1, draft=False, output_format="json")
    
    import json
    data = json.loads(brief)
    
    assert "leads" in data
    assert "date" in data
    assert len(data["leads"]) >= 1