"""One view of an organisation's brand for every product: the BrandForge analysis in the tenant's schema (logo,
colours, fonts, voice) and the products the account holds. Each fact says where it came from. Nothing is guessed:
an account that never ran BrandForge gets an empty brand, and a renderer draws its no-logo, no-accent form."""
from __future__ import annotations

from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional

GENERIC = {"serif", "sans-serif", "monospace", "system-ui", "cursive", "fantasy", "ui-sans-serif", "ui-serif"}
ROLES = ("heading", "text", "button")


@dataclass
class Product:
    name: str
    url: Optional[str] = None
    image: Optional[str] = None
    price: Optional[str] = None
    currency: Optional[str] = None
    description: Optional[str] = None
    source: str = "catalogue"


@dataclass
class Brand:
    name: Optional[str] = None
    logo: Optional[str] = None
    primary: Optional[str] = None
    accent: Optional[str] = None
    palette: List[str] = field(default_factory=list)
    fonts: Dict[str, str] = field(default_factory=dict)    # heading, text, button -> CSS stack; *_weight -> "600"
    summary: Optional[str] = None
    tone: List[str] = field(default_factory=list)
    products: List[Product] = field(default_factory=list)
    social: List[Dict[str, str]] = field(default_factory=list)   # [{"name": "instagram", "url": ...}], from the site's own links
    address: Optional[str] = None
    sources: Dict[str, str] = field(default_factory=dict)   # fact -> where it came from

    def values(self) -> Dict[str, Any]:
        """The brand as template values."""
        out = {"brand.name": self.name, "brand.logo": self.logo, "brand.primary": self.primary,
               "brand.accent": self.accent, "brand.fonts": self.fonts or None, "brand.social": self.social or None,
               "brand.address": self.address}
        return {k: v for k, v in out.items() if v}


SOCIAL_HOSTS = ("instagram.com", "facebook.com", "linkedin.com", "x.com", "twitter.com", "youtube.com", "tiktok.com", "pinterest.com")


def social_from(raw: dict) -> List[Dict[str, str]]:
    """The site's own social links, one per network, from the links BrandForge crawled."""
    found: Dict[str, str] = {}
    for link in raw.get("links") or []:
        url = link.get("url") if isinstance(link, dict) else link
        if not isinstance(url, str):
            continue
        host = url.split("//", 1)[-1].split("/", 1)[0].lower().removeprefix("www.")
        network = next((h.split(".")[0] for h in SOCIAL_HOSTS if host == h or host.endswith("." + h)), None)
        if network and network not in found and url.rstrip("/").count("/") >= 3:
            found[network] = url
    return [{"name": n, "url": u} for n, u in found.items()]


def _quoted(family: str) -> str:
    return family if family.lower() in GENERIC else '"' + family.replace('"', "") + '"'


def stack_for(measured: dict, site_fonts: list) -> Optional[str]:
    """The CSS stack for one measured role: the family really drawn, the site's own fallbacks, the generic keyword
    the site ends its stacks with. A monospace on the page (code blocks) never ends a text stack."""
    family = str((measured or {}).get("family") or "").strip()
    if not family:
        return None
    names = [family] + [str(f).strip() for f in (measured.get("stack") or []) if str(f).strip() and str(f).strip() != family]
    if not any(n.lower() in GENERIC for n in names):
        ending = measured.get("fallback") or next((str(f).strip() for f in site_fonts or []
                                                   if str(f).strip().lower() in GENERIC and str(f).strip().lower() != "monospace"), None)
        if ending:
            names.append(ending)
    return ", ".join(_quoted(n) for n in names)


def fonts_from(row: dict) -> Dict[str, str]:
    full = (row or {}).get("full_result") or {}
    raw = (row or {}).get("raw_extraction") or {}
    typography = full.get("typography") or ((raw.get("computed_styles") or {}).get("typography")) or {}
    site_fonts = ((raw.get("computed_styles") or {}).get("fonts")) or [f.get("family") for f in full.get("fonts") or [] if isinstance(f, dict)]
    fonts = {role: stack for role in ROLES if (stack := stack_for(typography.get(role), site_fonts))}
    if not fonts:
        return {}
    for role in ROLES:
        fonts.setdefault(role, fonts.get("text") or fonts.get("heading"))
    for role in ("heading", "button"):
        weight = str((typography.get(role) or typography.get("text") or {}).get("weight") or "")
        if weight.isdigit():
            fonts[f"{role}_weight"] = weight
    return fonts


def brand_from(row: Optional[dict]) -> Brand:
    """A Brand from a BrandForge analysis row (brand_name, full_result, raw_extraction). Empty when there is none."""
    if not row:
        return Brand()
    full = row.get("full_result") or {}
    raw = row.get("raw_extraction") or {}
    palette = (full.get("colors") or {}).get("palette") or []
    best = lambda role: max((p for p in palette if p.get("role") == role), key=lambda p: p.get("score", 0), default=None)  # noqa: E731
    ui = [str(c) for c in (full.get("ui_palette") or [])]
    primary = (best("primary") or {}).get("hex") or (ui[0] if ui else None)
    accent = (best("accent") or {}).get("hex") or (ui[1] if len(ui) > 1 else None)
    logos = raw.get("logo_candidates") or []
    logo = next((c.get("url") for c in logos if c.get("is_header") and c.get("url")), None) or (logos[0].get("url") if logos else None)
    summary = full.get("brand_summary")
    summary = summary.get("summary") if isinstance(summary, dict) else summary
    name = row.get("brand_name")
    if not name and isinstance(full.get("brand"), dict):
        name = full["brand"].get("name")
    tone = full.get("tone")
    tone = tone if isinstance(tone, list) else list((tone or {}).get("descriptors") or []) if isinstance(tone, dict) else []
    brand = Brand(name=name, logo=logo, primary=primary, accent=accent, palette=ui, fonts=fonts_from(row), summary=summary,
                  tone=[str(t) for t in tone], social=social_from(raw))
    brand.sources = {k: "brandforge" for k, v in brand.values().items() if v}
    return brand


def read_brand(conn, schema: str, products: bool = True) -> Brand:
    """The organisation's brand from its schema: the newest BrandForge analysis, and its product catalogue when it
    holds one. A schema with neither gives an empty Brand."""
    row = None
    if _exists(conn, schema, "brandforge_analyses"):
        got = conn.execute(f'SELECT brand_name, url, full_result, raw_extraction FROM "{schema}".brandforge_analyses '
                           "ORDER BY created_at DESC NULLS LAST LIMIT 1").fetchone()
        if got:
            row = dict(zip(("brand_name", "url", "full_result", "raw_extraction"), got))
    brand = brand_from(row)
    if products:
        brand.products = read_products(conn, schema)
    return brand


def read_products(conn, schema: str, limit: int = 50) -> List[Product]:
    """The account's products as its catalogue states them (Aivora's strategist_products today)."""
    if not _exists(conn, schema, "strategist_products"):
        return []
    rows = conn.execute(f'SELECT name, description, image_url, product_url FROM "{schema}".strategist_products '
                        f"WHERE coalesce(name, '') <> '' ORDER BY name LIMIT {int(limit)}").fetchall()
    return [Product(name=n, description=d, image=i, url=u, source="catalogue") for n, d, i, u in rows]


def _exists(conn, schema: str, table: str) -> bool:
    return conn.execute("SELECT 1 FROM information_schema.tables WHERE table_schema = %s AND table_name = %s",
                        (schema, table)).fetchone() is not None
