"""Generate domestic offer-card HTML from read-only offer data."""
import os

import markdown
from flask import render_template

from InvestmentManager import offers_store
from modules.core import offer_media, storage_paths


class OfferNotFound(LookupError):
    pass


def _normalize_value(value):
    if value is None:
        return ""
    text = str(value).strip()
    return "" if text.lower() == "nd" else text


def _localization_text(offer):
    raw_location = _normalize_value(offer.get("Lokalizacja"))
    if raw_location:
        return raw_location
    parts = [
        _normalize_value(offer.get("Ulica")),
        _normalize_value(offer.get("Miejscowosc")),
        _normalize_value(offer.get("Wojewodztwo")),
    ]
    return ", ".join(part for part in parts if part)


def _main_image_url(offer_id, base_url):
    directory = offer_media.offer_directory(offer_id)
    for extension in (".jpg", ".jpeg", ".png", ".webp"):
        filename = offer_media.image_filename(offer_id, 0, extension)
        if os.path.isfile(directory / filename):
            return f"{base_url}/static/images/{offer_id}/{filename}"
    return f"{base_url}/static/images/icon.png"


def _shorten_text(text, max_length=400):
    if not text:
        return ""
    compact = " ".join(str(text).split())
    if len(compact) <= max_length:
        return compact
    return f"{compact[:max_length].rstrip()}... Więcej szczegółów w biurze. Zapraszamy!"


def _agent_data(agent_id):
    row = offers_store.get_offer_card_agent(agent_id)
    return {
        "first_name": _normalize_value(row[0]) if row else "",
        "last_name": _normalize_value(row[1]) if row else "",
        "email": _normalize_value(row[2]) if row else "",
        "phone": _normalize_value(row[3]) if row else "",
        "licence": _normalize_value(row[4]) if row else "",
    }


def generate_offer_card(offer_id, base_url):
    offer = offers_store.get_offer_card_data(offer_id)
    if offer is None:
        raise OfferNotFound
    agent = _agent_data(offer.get("ID_agenta"))
    offer["Lokalizacja"] = _localization_text(offer)
    description = markdown.markdown(
        _shorten_text(offer_media.read_description_text(offer_id), 400)
    )
    return render_template(
        "investmentmanager/offer_card_template.html",
        row=offer,
        description=description,
        img_url=_main_image_url(offer_id, base_url),
        agent=agent,
    )


def _safe_hex_color(raw_value, default_value):
    value = str(raw_value or "").strip()
    if not value:
        return default_value
    if len(value) == 7 and value.startswith("#"):
        hex_part = value[1:]
        if all(character in "0123456789abcdefABCDEF" for character in hex_part):
            return value.lower()
    return default_value


def _variant(raw_value):
    return "print" if str(raw_value or "").strip().lower() == "print" else "facebook"


def _headline(offer):
    property_type = _normalize_value(offer.get("Typ_nieruchomosci")).upper()
    offer_type = _normalize_value(offer.get("Typ_oferty")).upper()
    if property_type and offer_type:
        return f"{property_type} NA {offer_type}"
    return property_type or "OFERTA"


def _image_urls(offer_id, base_url, limit=2):
    filenames = offer_media.list_image_filenames(offer_id, numeric_sort=True)
    return [f"{base_url}/static/images/{offer_id}/{name}" for name in filenames[:limit]]


def resolve_agent_avatar_url(agent_id, base_url):
    if agent_id is not None:
        for extension in ("jpg", "jpeg", "png", "webp"):
            filename = f"agent_{agent_id}.{extension}"
            if os.path.isfile(storage_paths.agent_avatar_dir() / filename):
                return f"{base_url}/static/images/{filename}"
    return f"{base_url}/static/images/icon.png"


def generate_announcement_card(offer_id, base_url, bg, accent, variant):
    offer = offers_store.get_offer_card_data(offer_id)
    if offer is None:
        raise OfferNotFound
    agent = _agent_data(offer.get("ID_agenta"))
    image_urls = _image_urls(offer_id, base_url)
    main_image_url = image_urls[0] if image_urls else _main_image_url(offer_id, base_url)
    side_image_url = image_urls[1] if len(image_urls) > 1 else main_image_url
    selected_variant = _variant(variant)
    description = markdown.markdown(
        _shorten_text(offer_media.read_description_text(offer_id), 1600)
    )
    template = (
        "investmentmanager/offer_announcement_card_print_template.html"
        if selected_variant == "print"
        else "investmentmanager/offer_announcement_card_template.html"
    )
    rendered = render_template(
        template,
        row=offer,
        headline=_headline(offer),
        main_image_url=main_image_url,
        side_image_url=side_image_url,
        theme_bg=_safe_hex_color(bg, "#ffffff"),
        theme_accent=_safe_hex_color(accent, "#9ac0e4"),
        logo_url=f"{base_url}/static/images/investment_logo.webp",
        mfinanse_logo_url=f"{base_url}/static/images/mfinanse.webp",
        agent_avatar_url=resolve_agent_avatar_url(offer.get("ID_agenta"), base_url),
        agent=agent,
        description=description,
        variant=selected_variant,
    )
    prefix = "Ogloszenie_druk" if selected_variant == "print" else "Ogloszenie"
    return rendered, prefix
