"""Small helpers shared by templates, sitemaps, feeds and the agent API."""
import json
import re
from html import unescape

from django.conf import settings
from django.utils.html import strip_tags

WORDS_PER_MINUTE = 200


def site_url():
    return getattr(settings, 'SITE_URL', 'https://thereversetimes.com').rstrip('/')


def absolute(path_or_url):
    """Turn '/articles/x/' into 'https://thereversetimes.com/articles/x/'."""
    if not path_or_url:
        return ''
    value = str(path_or_url)
    if value.startswith(('http://', 'https://')):
        return value
    if not value.startswith('/'):
        value = '/' + value
    return site_url() + value


def plain_text(html):
    text = unescape(strip_tags(html or ''))
    return re.sub(r'\s+', ' ', text).strip()


def word_count(html):
    text = plain_text(html)
    return len(text.split()) if text else 0


def reading_minutes(html):
    words = word_count(html)
    return max(1, round(words / WORDS_PER_MINUTE)) if words else 1


def to_jsonld(data):
    """Serialise a dict for a <script type="application/ld+json"> block safely."""
    raw = json.dumps(data, ensure_ascii=False, separators=(',', ':'))
    # Prevent "</script>" inside content from closing the tag early.
    return raw.replace('</', '<\\/')


def organization_schema(site=None):
    same_as = []
    if site is not None:
        for field in ('social_facebook', 'social_twitter', 'social_instagram', 'social_youtube',
                      'social_linkedin', 'social_tiktok', 'social_threads', 'social_reddit'):
            url = (getattr(site, field, '') or '').strip()
            if url:
                if url.startswith('http://'):
                    url = 'https://' + url[len('http://'):]   # profile links must match the real https address
                same_as.append(url)
    if not same_as:
        same_as = ['https://www.youtube.com/@TheReverseTimes', 'https://www.facebook.com/thereversetimes']
    return {
        '@type': 'NewsMediaOrganization',
        '@id': absolute('/#organization'),
        'name': 'The Reverse Times',
        'alternateName': ['TheReverseTimes', 'Reverse Times', 'দ্য রিভার্স টাইমস', 'রিভার্স টাইমস',
                          'দ্য রিভার্স টাইমস ম্যাগাজিন', 'The Reverse Times Magazine'],
        'slogan': 'ইতিহাসের উল্টো পাতা থেকে',
        'url': absolute('/'),
        'logo': {
            '@type': 'ImageObject',
            'url': absolute('/static/img/logo-512.png'),
            'width': 512,
            'height': 512,
        },
        'description': (
            "The Reverse Times (thereversetimes.com) is Bangladesh's first historical magazine, "
            "founded in 2023. It publishes researched articles on the history of Bangladesh and "
            "Bengal, the naming history of places, heritage sites and archaeology, and sells "
            "history-inspired merchandise (Wearable History)."
        ),
        'foundingDate': '2023',
        'foundingLocation': {'@type': 'Place', 'name': 'Bangladesh'},
        'email': getattr(site, 'contact_email', '') or 'thereversetimer@gmail.com',
        'sameAs': same_as,
        'knowsAbout': [
            'History of Bangladesh', 'বাংলাদেশের ইতিহাস', 'হারিয়ে যাওয়া পেশা', 'স্থানের নামকরণের ইতিহাস',
            'বাংলা ইতিহাস ম্যাগাজিন', 'Ancient Bengal', 'Mughal Bengal', 'Bengal Sultanate',
            'Liberation War of Bangladesh 1971', 'Language Movement 1952', 'Bangladesh archaeology',
            'Naming history of places in Bangladesh',
        ],
    }


def website_schema():
    return {
        '@type': 'WebSite',
        '@id': absolute('/#website'),
        'name': 'The Reverse Times',
        # Google shows this as the site name. Never list the bare domain here, or Google may show the domain.
        'alternateName': ['দ্য রিভার্স টাইমস', 'Reverse Times'],
        'url': absolute('/'),
        'inLanguage': ['en', 'bn'],
        'publisher': {'@id': absolute('/#organization')},
        'potentialAction': {
            '@type': 'SearchAction',
            'target': {'@type': 'EntryPoint', 'urlTemplate': absolute('/search/?q={search_term_string}')},
            'query-input': 'required name=search_term_string',
        },
    }
