"""Tests for dgred writer — dry-run mode, no real HTTP."""

import logging
from datetime import datetime

from agent_samochodowy.config import Settings
from agent_samochodowy.dgred.client import DgredClient
from agent_samochodowy.dgred.writer import LeadWriter
from agent_samochodowy.models import MatchResult, Offer, PartQuery, Post


def _settings() -> Settings:
    return Settings(dgred_api_key="test", dry_run=True)


def _post(pid: str = "1", author: str = "Jan Kowalski") -> Post:
    return Post(
        post_id=pid,
        group="TIR części",
        author_name=author,
        author_profile_url=f"https://facebook.com/{author.replace(' ', '')}",
        text="Szukam pompy wody do Volvo FH13, numer 20744939",
        timestamp=datetime(2025, 1, 15, 10, 30),
        post_url=f"https://facebook.com/groups/tir/posts/{pid}",
    )


def _query() -> PartQuery:
    return PartQuery(
        is_part_request=True,
        raw_text="Szukam pompy wody do Volvo FH13, numer 20744939",
        brand="VOLVO",
        model="FH13",
        category="pompa wody",
        oe_numbers=["20744939"],
        reason="Zapytanie o pompę wody z numerem OE",
    )


def _match_result() -> MatchResult:
    return MatchResult(
        confidence=0.95,
        method="oe",
        offers=[
            Offer(
                offer_id="1",
                platform="allegro",
                url="https://allegro.pl/1",
                title="Pompa wody VOLVO FH13 20744939",
                price=450.0,
                oe_numbers=["20744939"],
            )
        ],
        matched=True,
    )


class TestDryRun:
    def test_dry_run_no_http(self, caplog):
        """In dry-run mode, no real HTTP calls are made."""
        settings = _settings()
        dgred = DgredClient(settings)
        writer = LeadWriter(dgred, settings)

        with caplog.at_level(logging.INFO):
            writer.write_lead(_post(), _query(), _match_result())

        # Should see DRY-RUN log messages
        assert any("[DRY-RUN]" in r.message for r in caplog.records)
        dgred.close()

    def test_client_dedup(self, caplog):
        """Same author → same client_id, not created twice."""
        settings = _settings()
        dgred = DgredClient(settings)
        writer = LeadWriter(dgred, settings)

        with caplog.at_level(logging.INFO):
            writer.write_lead(_post("1"), _query(), _match_result())
            writer.write_lead(_post("2"), _query(), _match_result())

        # Only one POST /clients call (the second should use cache)
        create_calls = [r for r in caplog.records if "POST /clients" in r.message and "notes" not in r.message]
        assert len(create_calls) == 1
        dgred.close()

    def test_no_match_lead(self, caplog):
        """Even with no match, a lead is created with 'Brak dopasowania' status."""
        settings = _settings()
        dgred = DgredClient(settings)
        writer = LeadWriter(dgred, settings)
        no_match = MatchResult(confidence=0.0, method="brak", matched=False)

        with caplog.at_level(logging.INFO):
            writer.write_lead(_post(), _query(), no_match)

        assert any("Brak dopasowania" in r.message for r in caplog.records)
        dgred.close()
