"""Inbound mail classifier, extraction, and idempotent processing."""

from __future__ import annotations

from datetime import date
from types import SimpleNamespace

from app.inbound_mail import (
    classify_message,
    extract_contact_name,
    extract_website,
    get_or_create_rules,
    is_pipe_tracking_spam_subject,
    process_account,
    rules_to_dict,
)
from app.models import InboundEmailEvent, Lead
from app.schemas import LeadCreate
from app import crud


def test_classify_positive():
    result = classify_message(
        subject="Re: proposal",
        body="Yes I'm interested, let's talk next week",
        filter_keywords=["proposal"],
        positive_keywords=["interested", "let's talk"],
        negative_keywords=["not interested"],
        use_ai=False,
    )
    assert result["filter_matched"] is True
    assert result["classification"] == "positive"
    assert "interested" in result["matched_sentiment_terms"]


def test_classify_negative_wins_over_positive():
    result = classify_message(
        subject="demo",
        body="I was interested but please unsubscribe me",
        filter_keywords=["demo"],
        positive_keywords=["interested"],
        negative_keywords=["unsubscribe"],
        use_ai=False,
    )
    assert result["classification"] == "negative"


def test_classify_ignored_when_filter_misses():
    result = classify_message(
        subject="Hello",
        body="Random note",
        filter_keywords=["proposal", "audit"],
        positive_keywords=["interested"],
        negative_keywords=[],
        use_ai=False,
    )
    assert result["filter_matched"] is False
    assert result["classification"] == "ignored"


def test_classify_empty_filter_processes_all():
    result = classify_message(
        subject="Hi",
        body="We are interested",
        filter_keywords=[],
        positive_keywords=["interested"],
        negative_keywords=[],
        use_ai=False,
    )
    assert result["filter_matched"] is True
    assert result["classification"] == "positive"


def test_classify_skipped_without_sentiment():
    result = classify_message(
        subject="proposal follow up",
        body="Got your note",
        filter_keywords=["proposal"],
        positive_keywords=["interested"],
        negative_keywords=["unsubscribe"],
        use_ai=False,
    )
    assert result["classification"] == "skipped"


def test_classify_azure_crystal_nature_spam_filtered_out():
    """Subjects like 'Name, … | CODE azure.crystal.nature' must not become leads."""
    result = classify_message(
        subject="Celine, i need to pick your brain on this | QRV7G00 azure.crystal.nature",
        body="Let's talk about pricing and a demo",
        filter_keywords=[],
        positive_keywords=["interested", "let's talk", "pricing", "demo"],
        negative_keywords=[],
        use_ai=False,
    )
    assert result["filter_matched"] is True
    assert result["classification"] == "negative"
    assert "pipe-tracking-subject" in result["matched_sentiment_terms"]


def test_pipe_tracking_spam_without_brand_string():
    """Brand like azure.crystal.nature is not required; `|` + track code is enough."""
    assert is_pipe_tracking_spam_subject(
        "Hannah, let's share ideas | TQNZ5F8 other.brand.here"
    )
    assert is_pipe_tracking_spam_subject("John, we can do this! | W5MMQV2")
    assert is_pipe_tracking_spam_subject(
        "GANGA would you like more specifics? | some.brand SP3XAET"
    )
    assert not is_pipe_tracking_spam_subject("Q3 notes | Finance")
    assert not is_pipe_tracking_spam_subject("Meeting | John Smith")
    assert not is_pipe_tracking_spam_subject("Hello there")
    # Replies to our tracked outreach must NOT be hard-rejected
    assert not is_pipe_tracking_spam_subject(
        "Re: Celine, i need to pick your brain on this | QRV7G00 azure.crystal.nature"
    )
    assert not is_pipe_tracking_spam_subject(
        "Re: Re: Hannah, let's share ideas | TQNZ5F8 azure.crystal.nature"
    )

    result = classify_message(
        subject="Let's talk about it. | PAD7CXN",
        body="Interested in a demo",
        filter_keywords=[],
        positive_keywords=["interested", "let's talk", "demo"],
        negative_keywords=[],
        use_ai=False,
    )
    assert result["classification"] == "negative"


def test_reply_to_tracked_subject_can_be_ai_positive(monkeypatch):
    monkeypatch.setattr(
        "app.inbound_mail.classify_interest_with_openai",
        lambda **kwargs: {
            "label": "positive",
            "reason": "interested reply to outreach",
            "confidence": 0.91,
            "source": "openai",
        },
    )
    result = classify_message(
        subject="Re: Celine, i need to pick your brain on this | QRV7G00 azure.crystal.nature",
        body="Yes I'm interested — let's book a demo and share pricing.",
        filter_keywords=[],
        positive_keywords=[],
        # Legacy brand keyword must not block Re: prospect replies
        negative_keywords=["azure.crystal.nature", "unsubscribe"],
        from_email="prospect@acme.co",
        from_name="Alex",
        use_ai=True,
    )
    # Still negative if azure is in keywords and we match whole blob — so
    # classify should ignore outreach-brand negatives on reply subjects.
    assert result["classification"] == "positive"


def test_classify_ai_positive_creates_signal(monkeypatch):
    monkeypatch.setattr(
        "app.inbound_mail.classify_interest_with_openai",
        lambda **kwargs: {
            "label": "positive",
            "reason": "wants demo",
            "confidence": 0.9,
            "source": "openai",
        },
    )
    result = classify_message(
        subject="Quick question",
        body="Can we book a call next week about your package?",
        filter_keywords=[],
        positive_keywords=[],
        negative_keywords=[],
        from_email="alex@acme.co",
        from_name="Alex",
        use_ai=True,
    )
    assert result["classification"] == "positive"
    assert any(t.startswith("ai:") for t in result["matched_sentiment_terms"])


def test_classify_ai_rejects_newsletter_even_with_yes(monkeypatch):
    monkeypatch.setattr(
        "app.inbound_mail.classify_interest_with_openai",
        lambda **kwargs: {
            "label": "negative",
            "reason": "newsletter",
            "confidence": 0.9,
            "source": "openai",
        },
    )
    result = classify_message(
        subject="Reminder: Information Technology Rules",
        body="yes you can manage notifications … unsubscribe",
        filter_keywords=[],
        positive_keywords=["yes", "interested"],
        negative_keywords=[],
        from_email="messages-noreply@linkedin.com",
        use_ai=True,
    )
    assert result["classification"] == "negative"


def test_classify_ai_automated_heuristic_without_api(monkeypatch):
    # Even with use_ai=True, automated senders short-circuit in inbound_ai
    result = classify_message(
        subject="Your weekly digest",
        body="Lots of updates yes",
        filter_keywords=[],
        positive_keywords=["yes"],
        negative_keywords=[],
        from_email="noreply@updates.example.com",
        use_ai=True,
    )
    assert result["classification"] == "negative"
    assert any("automated-sender" in t for t in result["matched_sentiment_terms"])


def test_extract_website_and_name():
    assert extract_website("See https://acme.co/pricing thanks") == "https://acme.co/pricing"
    assert extract_contact_name("Alex Rivera", "alex@acme.co") == "Alex Rivera"
    assert extract_contact_name("", "alex.rivera@acme.co") == "Alex Rivera"


def test_process_account_creates_lead_and_is_idempotent(db, monkeypatch):
    rules_row = get_or_create_rules(db)
    rules = rules_to_dict(rules_row)
    rules["filter_keywords"] = ["proposal"]
    rules["positive_keywords"] = ["interested"]
    rules["negative_keywords"] = ["unsubscribe"]

    account = SimpleNamespace(
        email="seller@gmail.com",
        scopes="https://www.googleapis.com/auth/gmail.readonly",
        token_json="{}",
    )

    stubs = [{"id": "msg-1", "threadId": "t-1"}]
    detail = {
        "id": "msg-1",
        "thread_id": "t-1",
        "from_name": "Casey Buyer",
        "from_email": "casey@buyer.co",
        "subject": "Re: proposal",
        "body": "Hi — interested in a demo. https://buyer.co",
        "snippet": "interested in a demo",
        "internal_date": 0,
    }

    monkeypatch.setattr("app.inbound_mail.account_has_readonly", lambda _a: True)
    monkeypatch.setattr("app.inbound_mail.list_recent_messages", lambda *a, **k: stubs)
    monkeypatch.setattr("app.inbound_mail.get_message_detail", lambda *a, **k: detail)
    monkeypatch.setattr("app.inbound_mail.ai_classify_enabled", lambda: False)

    first = process_account(db, account, rules)
    assert first["created"] == 1
    lead = db.query(Lead).filter(Lead.client_email == "casey@buyer.co").one()
    assert lead.stage == "Positive lead"
    assert lead.our_email == "seller@gmail.com"
    assert lead.website == "https://buyer.co"
    assert db.query(InboundEmailEvent).count() == 1

    second = process_account(db, account, rules)
    assert second["created"] == 0
    assert second["processed"] == 0  # already processed → skipped before count
    assert db.query(Lead).filter(Lead.client_email == "casey@buyer.co").count() == 1
    assert db.query(InboundEmailEvent).count() == 1


def test_process_account_ai_positive_creates_lead(db, monkeypatch):
    rules = {
        "filter_keywords": [],
        "positive_keywords": [],
        "negative_keywords": [],
    }
    account = SimpleNamespace(email="seller@gmail.com")
    stubs = [{"id": "msg-ai-1", "threadId": "t-ai-1"}]
    detail = {
        "id": "msg-ai-1",
        "thread_id": "t-ai-1",
        "from_name": "Jordan Lee",
        "from_email": "jordan@prospect.io",
        "subject": "Following up",
        "body": "Thanks for reaching out — can we schedule a call Thursday?",
        "snippet": "schedule a call Thursday",
        "internal_date": 0,
    }
    monkeypatch.setattr("app.inbound_mail.account_has_readonly", lambda _a: True)
    monkeypatch.setattr("app.inbound_mail.list_recent_messages", lambda *a, **k: stubs)
    monkeypatch.setattr("app.inbound_mail.get_message_detail", lambda *a, **k: detail)
    monkeypatch.setattr("app.inbound_mail.ai_classify_enabled", lambda: True)
    monkeypatch.setattr(
        "app.inbound_mail.classify_interest_with_openai",
        lambda **kwargs: {
            "label": "positive",
            "reason": "wants to schedule call",
            "confidence": 0.92,
            "source": "openai",
        },
    )

    stats = process_account(db, account, rules)
    assert stats["created"] == 1
    lead = db.query(Lead).filter(Lead.client_email == "jordan@prospect.io").one()
    assert lead.stage == "Positive lead"
    ev = db.query(InboundEmailEvent).one()
    assert ev.classification == "positive"
    assert "ai:" in (ev.matched_sentiment_terms or "")


def test_process_account_duplicate_existing_lead(db, monkeypatch):
    crud.create_lead(
        db,
        LeadCreate(
            contact_name="Casey",
            client_email="casey@buyer.co",
            our_email="seller@gmail.com",
            date_added=date.today(),
            stage="New Lead",
        ),
    )
    rules = {
        "filter_keywords": [],
        "positive_keywords": ["interested"],
        "negative_keywords": [],
    }
    account = SimpleNamespace(email="seller@gmail.com")
    stubs = [{"id": "msg-2", "threadId": "t-2"}]
    detail = {
        "id": "msg-2",
        "thread_id": "t-2",
        "from_name": "Casey",
        "from_email": "casey@buyer.co",
        "subject": "Hi",
        "body": "Still interested",
        "snippet": "Still interested",
        "internal_date": 0,
    }
    monkeypatch.setattr("app.inbound_mail.account_has_readonly", lambda _a: True)
    monkeypatch.setattr("app.inbound_mail.list_recent_messages", lambda *a, **k: stubs)
    monkeypatch.setattr("app.inbound_mail.get_message_detail", lambda *a, **k: detail)
    monkeypatch.setattr("app.inbound_mail.ai_classify_enabled", lambda: False)

    stats = process_account(db, account, rules)
    assert stats["duplicate"] == 1
    assert stats["created"] == 0
    ev = db.query(InboundEmailEvent).one()
    assert ev.classification == "duplicate"
