"""Generate reply proposals for status-67 (Dopasowano) leads.

Builds a short, natural PL message ready for Denis to copy-paste.
Multiple template variants are rotated to avoid looking robotic.
NO auto-sending — text only.
"""

from __future__ import annotations

import random

from agent_samochodowy.models import MatchResult, Offer, PartQuery, Post

# ---------------------------------------------------------------------------
# Template variants — all must use {part}, {vehicle}, {url}, {price}
# ---------------------------------------------------------------------------
TEMPLATES = [
    "Cześć, widziałem że szukasz {part} do {vehicle} — mam taką w ofercie: {url}, cena {price}. Pisz jak zainteresowany.",
    "Hej! Mam {part} pasującą do {vehicle}: {url} ({price}). Daj znać jeśli Cię interesuje!",
    "Dzień dobry, mam w ofercie {part} do {vehicle}: {url}, cena {price}. Zapraszam do kontaktu!",
    "Cześć! Mam {part} do {vehicle}, szczegóły tutaj: {url} — cena {price}. Napisz jeśli pasuje.",
    "Hej, widzę że potrzebujesz {part} do {vehicle}. Mam taką: {url} za {price}. Odezwij się!",
]


def _describe_part(query: PartQuery, offer: Offer | None) -> str:
    """Human-readable part description from query or top offer."""
    if query.category:
        return query.category.lower()
    if offer and offer.title:
        return offer.title[:60]
    return "część"


def _describe_vehicle(query: PartQuery) -> str:
    """Human-readable vehicle from query fields."""
    parts = [p for p in (query.brand, query.model, query.year) if p]
    return " ".join(parts) if parts else "Twojego pojazdu"


def _format_price(offer: Offer | None) -> str:
    if offer and offer.price is not None:
        currency = offer.currency or "PLN"
        # Format price: strip trailing zeros for whole numbers
        if offer.price == int(offer.price):
            return f"{int(offer.price)} {currency}"
        return f"{offer.price:.2f} {currency}"
    return "do uzgodnienia"


def generate_reply_proposal(
    post: Post,
    query: PartQuery,
    result: MatchResult,
    *,
    template_index: int | None = None,
) -> dict:
    """Build a reply proposal for a Dopasowano lead.

    Returns dict with keys:
        reply_text:      ready-to-send message
        offer_url:       direct link to the top matched offer
        author_profile:  link to the FB author profile
        template_id:     which template was used (0-based)
    """
    top_offer = result.offers[0] if result.offers else None

    part = _describe_part(query, top_offer)
    vehicle = _describe_vehicle(query)
    offer_url = top_offer.url if top_offer else ""
    price = _format_price(top_offer)

    idx = template_index if template_index is not None else random.randrange(len(TEMPLATES))
    idx = idx % len(TEMPLATES)

    reply_text = TEMPLATES[idx].format(
        part=part,
        vehicle=vehicle,
        url=offer_url,
        price=price,
    )

    return {
        "reply_text": reply_text,
        "offer_url": offer_url,
        "author_profile": post.author_profile_url,
        "template_id": idx,
    }
