"""Penyusun structured data (JSON-LD) untuk mesin pencari.

Structured data adalah cara memberi tahu Google *apa arti* sebuah halaman —
bukan sekadar tulisan apa yang ada di dalamnya. Hasilnya: kartu profil di panel
kanan hasil pencarian, dan artikel yang tampil lengkap dengan tanggal & penulis.
"""

from django.urls import reverse


def absolute(request, path_or_url):
    """Ubah path relatif jadi URL lengkap. Google menolak URL relatif di JSON-LD."""
    if not path_or_url:
        return ""
    if path_or_url.startswith("http"):
        return path_or_url
    return request.build_absolute_uri(path_or_url)


def _image_url(request, profile, setting):
    """Gambar perwakilan situs: og_image, lalu foto profil, lalu kosong."""
    for candidate in (getattr(setting, "og_image", None), getattr(profile, "photo", None)):
        if candidate:
            return absolute(request, candidate.url)
    return ""


def person_schema(request, profile, setting, social_links=()):
    """Identitas pemilik situs."""
    data = {
        "@context": "https://schema.org",
        "@type": "Person",
        "name": profile.full_name,
        "url": absolute(request, reverse("core:home")),
        "jobTitle": profile.headline,
    }
    if profile.bio:
        data["description"] = profile.bio
    image = _image_url(request, profile, setting)
    if image:
        data["image"] = image
    if profile.email:
        data["email"] = profile.email
    if profile.location:
        data["address"] = {"@type": "PostalAddress", "addressLocality": profile.location}
    urls = [link.url for link in social_links if link.url]
    if urls:
        data["sameAs"] = urls
    return data


def website_schema(request, profile, setting):
    """Identitas situs, sekaligus mendaftarkan kotak pencarian ke Google."""
    home = absolute(request, reverse("core:home"))
    search = absolute(request, reverse("core:search"))
    return {
        "@context": "https://schema.org",
        "@type": "WebSite",
        "name": setting.site_name or profile.full_name,
        "url": home,
        "inLanguage": "id-ID",
        "potentialAction": {
            "@type": "SearchAction",
            "target": {"@type": "EntryPoint", "urlTemplate": f"{search}?q={{search_term_string}}"},
            "query-input": "required name=search_term_string",
        },
    }


def article_schema(request, post, profile, setting):
    """Satu tulisan blog."""
    data = {
        "@context": "https://schema.org",
        "@type": "BlogPosting",
        "headline": post.title[:110],
        "url": absolute(request, post.get_absolute_url()),
        "mainEntityOfPage": absolute(request, post.get_absolute_url()),
        "inLanguage": "id-ID",
        "author": {"@type": "Person", "name": profile.full_name},
        "publisher": {"@type": "Person", "name": profile.full_name},
        "wordCount": post.reading_time * 200,
    }
    if post.excerpt:
        data["description"] = post.excerpt
    if post.published_at:
        data["datePublished"] = post.published_at.isoformat()
    if post.updated_at:
        data["dateModified"] = post.updated_at.isoformat()
    if post.cover:
        data["image"] = absolute(request, post.cover.url)
    else:
        fallback = _image_url(request, profile, setting)
        if fallback:
            data["image"] = fallback
    if post.category:
        data["articleSection"] = post.category.name
    keywords = [tag.name for tag in post.tags.all()]
    if keywords:
        data["keywords"] = ", ".join(keywords)
    return data


def project_schema(request, project, profile):
    """Satu proyek portofolio."""
    data = {
        "@context": "https://schema.org",
        "@type": "CreativeWork",
        "name": project.title,
        "url": absolute(request, project.get_absolute_url()),
        "inLanguage": "id-ID",
        "creator": {"@type": "Person", "name": profile.full_name},
    }
    if project.short_description:
        data["description"] = project.short_description
    if project.thumbnail:
        data["image"] = absolute(request, project.thumbnail.url)
    if project.started_at:
        data["dateCreated"] = project.started_at.isoformat()
    tech = [skill.name for skill in project.tech_stack.all()]
    if tech:
        data["keywords"] = ", ".join(tech)
    return data


def breadcrumb_schema(request, trail):
    """trail: list of (nama, path)."""
    return {
        "@context": "https://schema.org",
        "@type": "BreadcrumbList",
        "itemListElement": [
            {
                "@type": "ListItem",
                "position": i,
                "name": name,
                "item": absolute(request, path),
            }
            for i, (name, path) in enumerate(trail, start=1)
        ],
    }
