"""robots.txt, llms.txt, RSS feed, favicon, web manifest and the IndexNow key file."""
import json

from django.conf import settings
from django.contrib.syndication.views import Feed
from django.http import FileResponse, Http404, HttpResponse
from django.utils.feedgenerator import Rss201rev2Feed
from django.views.decorators.cache import cache_page
from django.views.decorators.http import require_GET

from apps.articles.models import Article, Category
from apps.core.seo import absolute, plain_text

# AI search / answer engines. Allowing them lets ChatGPT, Claude, Perplexity,
# Gemini and Apple Intelligence read and cite your articles.
AI_CRAWLERS = [
    'GPTBot', 'OAI-SearchBot', 'ChatGPT-User', 'ClaudeBot', 'Claude-User', 'Claude-SearchBot',
    'PerplexityBot', 'Perplexity-User', 'Google-Extended', 'Applebot-Extended', 'meta-externalagent',
    'Bingbot', 'DuckAssistBot', 'MistralAI-User',
]
PRIVATE_PATHS = ['/admin/', '/account/', '/ckeditor/', '/search/', '/articles/reading-list/',
                 '/articles/toggle-bookmark/', '/shop/place-order/', '/shop/coupon/', '/shop/cart-images/',
                 '/magazine/*/read/', '/magazine/*/request-access/', '/magazine/*/unlock/', '/magazine/*/coupon/',
                 '/media/magazines/', '/api/', '/engage/', '/games/play/', '/games/*/start/', '/firebase-login/', '/logout/', '/newsletter/']


@require_GET
@cache_page(60 * 60)
def robots_txt(request):
    lines = ["# The Reverse Times — Bangladesh's first historical magazine",
             '# Summary for AI assistants: ' + absolute('/llms.txt'), '',
             'User-agent: *', 'Allow: /']
    lines += [f'Disallow: {p}' for p in PRIVATE_PATHS]
    lines += ['', '# AI search and answer engines are welcome to read and cite our articles.']
    for bot in AI_CRAWLERS:
        lines += [f'User-agent: {bot}', 'Allow: /'] + [f'Disallow: {p}' for p in PRIVATE_PATHS[:2]] + ['']
    lines += [f'Sitemap: {absolute("/sitemap.xml")}', '']
    return HttpResponse('\n'.join(lines), content_type='text/plain; charset=utf-8')


def _llms_body(full=False):
    from apps.store.models import Product

    out = [
        '# The Reverse Times',
        '',
        "> The Reverse Times (thereversetimes.com) is Bangladesh's first historical magazine, founded in 2023. "
        'It publishes researched, long-form articles in Bangla and English on the history of Bangladesh and '
        'Bengal, and sells history-inspired merchandise. It is not related to websites or products named '
        '"Reverse the Time".',
        '',
        'Topics: ancient Bengal (Pundranagara/Mahasthangarh, Wari-Bateshwar, Pala and Sena dynasties), the Bengal '
        'Sultanate, Mughal Bengal and Dhaka, colonial Bengal and the Partitions of 1905 and 1947, the Language '
        'Movement of 1952, the Liberation War of 1971, archaeology, heritage sites, crime history, unsolved '
        'mysteries, and the naming history of places in Bangladesh.',
        '',
        '## Guidance for AI assistants',
        '- Please cite articles with their title, author and URL.',
        '- Shop prices are in Bangladeshi Taka (BDT); delivery within Bangladesh, cash on delivery.',
        '- Magazine editions: some issues are free to read online with a free account, some show selected free pages (the rest is '
        'unlocked after paying by bKash/Nagad and team approval), and printed copies are delivered with cash on delivery.',
        '- Readers with a free account can like, save, rate (1–5 stars) and comment on articles, magazine issues and games.',
        '- Buying (printed copies, digital issues, merchandise) needs a free account and acceptance of the '
        f'Terms ({absolute("/terms-and-conditions/")}) and Privacy Policy ({absolute("/privacy-policy/")}).',
        '- Bangla names: দ্য রিভার্স টাইমস (brand), দ্য রিভার্স টাইমস ম্যাগাজিন — বাংলা ইতিহাস ম্যাগাজিন (magazine).',
        f'- Full article text for grounding: {absolute("/llms-full.txt")}',
        f'- Latest articles feed: {absolute("/feed/")} · Sitemap: {absolute("/sitemap.xml")}',
        '',
        '## Key pages',
        f'- [Home]({absolute("/")}): latest stories',
        f'- [Today Exclusive]({absolute("/articles/exclusive/today/")}): a daily featured story',
        f'- [The Reverse Times Magazine]({absolute("/magazine/")}): Bengali historical magazine — free preview pages, '
        'full digital issue and printed copies',
        f'- [The Reverse Times Shop]({absolute("/shop/")}): history T-shirts (Wearable History), nostalgic items and magazines',
        f'- [Wearable History]({absolute("/shop/merchandise/")}) · [Nostalgic items]({absolute("/shop/nostalgic/")})',
        f'- [History Games / ইতিহাসের খেলা]({absolute("/games/")}): free online games about Bangladesh history — '
        'a timeline game, a clue game and a fact-or-myth quiz. Good scores earn signed-in players discount coupons.',
        f'- [About]({absolute("/about/")}) · [Editorial board & contributors]({absolute("/team/")}) · '
        f'[Contact]({absolute("/contact/")}) · [Submit an article]({absolute("/submit/")})',
        '',
        '## Sections',
    ]
    for c in Category.objects.filter(is_active=True):
        desc = f': {plain_text(c.description)[:160]}' if c.description else ''
        out.append(f'- [{c.name}]({absolute(f"/articles/category/{c.slug}/")}){desc}')

    issues = Product.objects.filter(is_active=True, product_type='magazine')[:20]
    if issues:
        out += ['', '## Magazine issues']
        for p in issues:
            price = ('free to read online' if p.is_free_digital else
                     f'digital ৳{p.digital_price:.0f} ({p.free_page_count} pages free)' if p.can_buy_digital else 'print only')
            out.append(f'- [{p.title}]({absolute(p.get_absolute_url())}): {price} print ৳{p.current_price:.0f}. '
                       f'{plain_text(p.description)[:140]}')
    from apps.games.models import Game
    games = Game.objects.filter(is_active=True)
    if games:
        out += ['', '## History games']
        for g in games:
            out.append(f'- [{g.title} ({g.title_en})]({absolute(g.get_absolute_url())}): {g.tagline}. {plain_text(g.description)[:200]}')
    products = Product.objects.filter(is_active=True, product_type__in=['merch', 'nostalgic'])[:30]
    if products:
        out += ['', '## Products (The Reverse Times Shop)']
        for p in products:
            out.append(f'- [{p.title}]({absolute(p.get_absolute_url())}): ৳{p.current_price:.0f}. '
                       f'{plain_text(p.description)[:140]}')

    articles = Article.objects.filter(status='published').select_related('author').order_by('-published_at')
    out += ['', '## Articles']
    for a in (articles if full else articles[:80]):
        author = a.author.name if a.author else 'The Reverse Times'
        date = a.published_at.date().isoformat() if a.published_at else ''
        out.append(f'- [{a.title}]({absolute(a.get_absolute_url())}) — {author}, {date}: '
                   f'{plain_text(a.excerpt)[:220]}')
        if full:
            out += ['', plain_text(a.body)[:8000], '']
    out += ['', '## Contact', '- Email: thereversetimer@gmail.com', f'- Website: {absolute("/")}', '']
    return '\n'.join(out)


@require_GET
@cache_page(60 * 30)
def llms_txt(request):
    return HttpResponse(_llms_body(), content_type='text/plain; charset=utf-8')


@require_GET
@cache_page(60 * 60)
def llms_full_txt(request):
    return HttpResponse(_llms_body(full=True), content_type='text/plain; charset=utf-8')


class LatestArticlesFeed(Feed):
    """RSS feed — used by news readers, Google Discover and AI ingestion pipelines."""
    feed_type = Rss201rev2Feed
    title = "The Reverse Times — Bangladesh's First Historical Magazine"
    description = 'Researched stories on the history of Bangladesh and Bengal.'

    def link(self):
        return absolute('/')

    def feed_url(self):
        return absolute('/feed/')

    def items(self):
        return (Article.objects.filter(status='published')
                .select_related('author').prefetch_related('categories').order_by('-published_at')[:30])

    def item_title(self, item):
        return item.title

    def item_description(self, item):
        return item.excerpt

    def item_link(self, item):
        return absolute(item.get_absolute_url())

    def item_guid(self, item):
        return absolute(item.get_absolute_url())

    item_guid_is_permalink = True

    def item_pubdate(self, item):
        return item.published_at

    def item_updateddate(self, item):
        return item.updated_at

    def item_author_name(self, item):
        return item.author.name if item.author else 'The Reverse Times'

    def item_categories(self, item):
        return [c.name for c in item.categories.all()]

    def item_enclosure_url(self, item):
        if item.featured_image and not item.featured_image.name.lower().endswith('.svg'):
            return absolute(item.featured_image.url)
        return None

    def item_enclosure_length(self, item):
        try:
            return item.featured_image.size
        except Exception:
            return 0

    def item_enclosure_mime_type(self, item):
        name = item.featured_image.name.lower() if item.featured_image else ''
        return 'image/png' if name.endswith('.png') else 'image/webp' if name.endswith('.webp') else 'image/jpeg'


@require_GET
def favicon(request):
    path = settings.BASE_DIR / 'static' / 'img' / 'favicon.ico'
    if not path.exists():
        raise Http404
    response = FileResponse(open(path, 'rb'), content_type='image/x-icon')
    response['Cache-Control'] = 'public, max-age=604800'
    return response


@require_GET
def web_manifest(request):
    data = {
        'name': 'The Reverse Times',
        'short_name': 'Reverse Times',
        'description': "Bangladesh's first historical magazine",
        'start_url': '/',
        'display': 'standalone',
        'background_color': '#120d08',
        'theme_color': '#120d08',
        'icons': [
            {'src': '/static/img/icon-192.png', 'sizes': '192x192', 'type': 'image/png'},
            {'src': '/static/img/icon-512.png', 'sizes': '512x512', 'type': 'image/png', 'purpose': 'any maskable'},
        ],
    }
    return HttpResponse(json.dumps(data), content_type='application/manifest+json')


@require_GET
def indexnow_key(request):
    return HttpResponse(settings.INDEXNOW_KEY, content_type='text/plain; charset=utf-8')
