"""
Generate a static sitemap.xml file for fitmtaani.com.
Includes all static pages + all published blog posts.

Usage:
    python manage.py generate_sitemap
    python manage.py generate_sitemap --output /path/to/public/sitemap.xml
"""
import os

from django.core.management.base import BaseCommand
from django.utils import timezone

from apps.content.models import BlogPost


SITE_URL = "https://www.fitmtaani.com"

STATIC_PAGES = [
    ("/", "daily", "1.0"),
    ("/features", "weekly", "0.9"),
    ("/pricing", "weekly", "0.9"),
    ("/about", "monthly", "0.7"),
    ("/news", "daily", "0.8"),
    ("/faq", "monthly", "0.6"),
    ("/help", "monthly", "0.5"),
    ("/contact", "monthly", "0.6"),
    ("/privacy", "yearly", "0.3"),
    ("/terms", "yearly", "0.3"),
    ("/login", "monthly", "0.4"),
    ("/register", "monthly", "0.5"),
    ("/onboarding", "monthly", "0.5"),
    ("/checkin", "monthly", "0.4"),
]


class Command(BaseCommand):
    help = "Generate a static sitemap.xml for fitmtaani.com"

    def add_arguments(self, parser):
        parser.add_argument(
            "--output", type=str, default=None,
            help="Output file path. Defaults to sitemap.xml in current directory.",
        )

    def handle(self, *args, **options):
        now = timezone.now().strftime("%Y-%m-%d")
        urls = []

        # Static pages
        for path, changefreq, priority in STATIC_PAGES:
            urls.append(
                f"  <url>\n"
                f"    <loc>{SITE_URL}{path}</loc>\n"
                f"    <lastmod>{now}</lastmod>\n"
                f"    <changefreq>{changefreq}</changefreq>\n"
                f"    <priority>{priority}</priority>\n"
                f"  </url>"
            )

        # Blog posts
        posts = BlogPost.objects.filter(status="published").only(
            "slug", "updated_at"
        ).order_by("-published_at")

        post_count = 0
        for post in posts.iterator(chunk_size=500):
            lastmod = post.updated_at.strftime("%Y-%m-%d") if post.updated_at else now
            urls.append(
                f"  <url>\n"
                f"    <loc>{SITE_URL}/news/{post.slug}</loc>\n"
                f"    <lastmod>{lastmod}</lastmod>\n"
                f"    <changefreq>monthly</changefreq>\n"
                f"    <priority>0.6</priority>\n"
                f"  </url>"
            )
            post_count += 1

        xml = (
            '<?xml version="1.0" encoding="UTF-8"?>\n'
            '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n'
            + "\n".join(urls)
            + "\n</urlset>\n"
        )

        output_path = options["output"] or "sitemap.xml"
        with open(output_path, "w", encoding="utf-8") as f:
            f.write(xml)

        self.stdout.write(self.style.SUCCESS(
            f"Sitemap generated: {os.path.abspath(output_path)} "
            f"({len(STATIC_PAGES)} static pages + {post_count} blog posts = {len(urls)} URLs)"
        ))
