"""Robots.txt and sitemap generator for Prism.

Generates robots.txt and a basic sitemap.xml for the frontend public directory.
"""

from __future__ import annotations

from pathlib import Path

from prisme.generators.base import GeneratedFile, GeneratorBase
from prisme.spec.stack import FileStrategy
from prisme.utils.template_engine import TemplateRenderer


class RobotsGenerator(GeneratorBase):
    """Generator for robots.txt and sitemap.xml."""

    REQUIRED_TEMPLATES = [
        "frontend/public/robots.txt.jinja2",
        "frontend/public/sitemap.xml.jinja2",
    ]

    # Default paths to disallow for crawlers
    DEFAULT_DISALLOW = [
        "/dashboard",
        "/admin",
        "/api/",
        "/graphql",
        "/settings",
        "/profile",
    ]

    # Default public pages for the sitemap
    DEFAULT_PAGES = [
        {"loc": "/", "changefreq": "weekly", "priority": "1.0"},
        {"loc": "/blog", "changefreq": "daily", "priority": "0.8"},
        {"loc": "/contact", "changefreq": "monthly", "priority": "0.5"},
    ]

    def __init__(self, *args, **kwargs) -> None:  # type: ignore[no-untyped-def]
        super().__init__(*args, **kwargs)
        # robots.txt and sitemap go into the frontend public directory
        frontend_base = Path(self.generator_config.frontend_output)
        # public/ is a sibling of src/ in a typical Vite project
        self.public_path = frontend_base.parent / "public"
        self.renderer = TemplateRenderer()
        self.renderer.validate_templates_exist(self.REQUIRED_TEMPLATES)

    def generate_files(self) -> list[GeneratedFile]:
        """Generate robots.txt and sitemap.xml."""
        files = []

        # robots.txt
        robots_content = self.renderer.render_file(
            "frontend/public/robots.txt.jinja2",
            context={
                "disallow_paths": self.DEFAULT_DISALLOW,
                "sitemap_url": "/sitemap.xml",
            },
        )
        files.append(
            GeneratedFile(
                path=self.public_path / "robots.txt",
                content=robots_content,
                strategy=FileStrategy.GENERATE_ONCE,
                description="robots.txt for search engine crawlers",
            )
        )

        # sitemap.xml
        sitemap_content = self.renderer.render_file(
            "frontend/public/sitemap.xml.jinja2",
            context={
                "urls": self.DEFAULT_PAGES,
            },
        )
        files.append(
            GeneratedFile(
                path=self.public_path / "sitemap.xml",
                content=sitemap_content,
                strategy=FileStrategy.GENERATE_ONCE,
                description="XML sitemap for search engines",
            )
        )

        return files


__all__ = ["RobotsGenerator"]
