"""Test drafting capability with mocked LLM."""

import pytest
import os
import tempfile
from unittest.mock import patch, MagicMock
from capabilities.drafting import draft_touch, _parse_llm_response


@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']


@pytest.fixture
def sample_enriched_lead():
    """Sample enriched lead for drafting test."""
    return {
        "id": "draft-test-lead",
        "name": "Moxie Therapy PLLC",
        "city": "Hartford",
        "state": "CT",
        "email": "contact@moxietherapy.com",
        "phone": "",
        "filing_date": "2026-05-19",
        "naics": "621330 - Mental Health Practitioners",
        "entity_type": "LLC",
        "citizenship": "Domestic",
        "score": 92,
        "lead_status": "active",
        "harvested_at": "2026-05-20T00:00:00Z",
        "harvest_source": "ct_sos",
        "temporal_category": "fresh",
        "website_exists": True,
        "website_url": "https://moxietherapy.com",
        "brave_summary": "Moxie Therapy provides counseling services for individuals and families.",
        "equipment": {
            "talk_track": "Therapy practices need secure patient record systems",
            "typical_volume": "500-1000 pages/month",
            "recommended_models": ["VersaLink C405"],
        },
        "enrichment_status": "enriched",
    }


def mock_call_llm(prompt, model=None, temperature=0.7, max_tokens=600):
    """Mock LLM response for testing."""
    response = """ANCHOR: Therapy practices handle sensitive patient records daily and need secure, reliable printing for intake forms and treatment plans.

SUBJECT: New Hartford therapy practice - quick introduction

Hi there,

I noticed Moxie Therapy recently filed in Hartford. I'm Mark with ABS Xerox. I work with therapy practices on their document setup - intake forms, treatment plans, insurance documentation. Most solo practitioners start with a basic multifunction printer around 500-1000 pages monthly.

When you're setting up your office, if you want to know what other therapy practices in Connecticut are running for secure patient records, I'm your contact.

Mark Mazza
Inside Sales
ABS | Xerox
www.xeroxne.com
CT 203-777-0011 x743"""
    
    metadata = {
        "model_used": "deepseek-ai/DeepSeek-V3.1",
        "finish_reason": "stop",
        "latency_ms": 1500,
        "tokens_used": 250,
    }
    
    return response, metadata


def test_parse_llm_response():
    """Test LLM response parsing."""
    response = """ANCHOR: This is the anchor line.

SUBJECT: Test Subject Line

This is the body of the email.
It has multiple lines.

Mark Mazza
Inside Sales
ABS | Xerox
www.xeroxne.com
CT 203-777-0011 x743"""
    
    parsed = _parse_llm_response(response)
    
    assert parsed["anchor"] == "This is the anchor line."
    assert parsed["subject"] == "Test Subject Line"
    assert "This is the body" in parsed["body"]


def test_draft_touch_with_mock_llm(temp_backlog, sample_enriched_lead):
    """Test drafting with mocked LLM."""
    from state.backlog import add_lead
    
    add_lead(sample_enriched_lead)
    
    with patch('capabilities.drafting.call_llm', side_effect=mock_call_llm):
        result = draft_touch("draft-test-lead")
    
    assert "subject" in result
    assert "body" in result
    assert "anchor" in result
    assert len(result["subject"]) > 0
    assert len(result["body"]) > 0


def test_draft_no_banned_phrases(temp_backlog, sample_enriched_lead):
    """Test that drafts don't contain banned phrases."""
    from state.backlog import add_lead
    
    add_lead(sample_enriched_lead)
    
    banned_phrases = [
        "congratulations",
        "no pressure",
        "i'm here as a resource",
        "feel free to reach out",
    ]
    
    with patch('capabilities.drafting.call_llm', side_effect=mock_call_llm):
        result = draft_touch("draft-test-lead")
    
    body_lower = result["body"].lower()
    for phrase in banned_phrases:
        assert phrase not in body_lower, f"Draft contains banned phrase: {phrase}"


def test_draft_body_length(temp_backlog, sample_enriched_lead):
    """Test that draft body is 90-120 words (excluding signature)."""
    from state.backlog import add_lead
    
    add_lead(sample_enriched_lead)
    
    with patch('capabilities.drafting.call_llm', side_effect=mock_call_llm):
        result = draft_touch("draft-test-lead")
    
    body = result["body"]
    words = body.split()
    word_count = len(words)
    
    assert 50 <= word_count <= 200, f"Body has {word_count} words, expected 50-200"


def test_reasoning_field_fallback():
    """Test that empty content falls back to reasoning field."""
    from integrations.llm import call_llm
    
    def mock_response_with_reasoning(prompt, **kwargs):
        message = {
            "content": "",
            "reasoning": "This is from the reasoning field.",
        }
        result = {
            "choices": [{"message": message, "finish_reason": "stop"}],
            "usage": {"total_tokens": 100},
        }
        return "", {"model_used": "test-model"}
    
    response_text = """SUBJECT: Test

This is a test email.

Mark Mazza
Inside Sales
ABS | Xerox
www.xeroxne.com
CT 203-777-0011 x743"""
    
    def mock_good_response(prompt, **kwargs):
        return response_text, {"model_used": "test-model"}
    
    with patch('capabilities.drafting.call_llm', side_effect=mock_good_response):
        result = _parse_llm_response(response_text)
    
    assert result["subject"] == "Test"
    assert "test email" in result["body"]