"""Tests for the robots.txt / sitemap generator."""

from __future__ import annotations

from pathlib import Path

import pytest

from prisme.generators.base import GeneratorContext
from prisme.generators.frontend.robots import RobotsGenerator
from prisme.spec.fields import FieldSpec, FieldType
from prisme.spec.model import ModelSpec
from prisme.spec.project import ProjectSpec
from prisme.spec.stack import FileStrategy, StackSpec


@pytest.fixture
def basic_stack() -> StackSpec:
    return StackSpec(
        name="test-project",
        version="1.0.0",
        models=[
            ModelSpec(
                name="Item",
                fields=[FieldSpec(name="name", type=FieldType.STRING, required=True)],
            )
        ],
    )


class TestRobotsGenerator:
    """Tests for RobotsGenerator."""

    def test_generates_robots_and_sitemap(self, basic_stack: StackSpec, tmp_path: Path) -> None:
        ctx = GeneratorContext(
            domain_spec=basic_stack,
            output_dir=tmp_path,
            dry_run=True,
            project_spec=ProjectSpec(name="test-project"),
        )
        gen = RobotsGenerator(ctx)
        files = gen.generate_files()
        assert len(files) == 2
        file_paths = [str(f.path) for f in files]
        assert any("robots.txt" in p for p in file_paths)
        assert any("sitemap.xml" in p for p in file_paths)

    def test_robots_uses_generate_once_strategy(
        self, basic_stack: StackSpec, tmp_path: Path
    ) -> None:
        ctx = GeneratorContext(
            domain_spec=basic_stack,
            output_dir=tmp_path,
            dry_run=True,
            project_spec=ProjectSpec(name="test-project"),
        )
        gen = RobotsGenerator(ctx)
        files = gen.generate_files()
        for f in files:
            assert f.strategy == FileStrategy.GENERATE_ONCE

    def test_robots_txt_has_user_agent(self, basic_stack: StackSpec, tmp_path: Path) -> None:
        ctx = GeneratorContext(
            domain_spec=basic_stack,
            output_dir=tmp_path,
            dry_run=True,
            project_spec=ProjectSpec(name="test-project"),
        )
        gen = RobotsGenerator(ctx)
        files = gen.generate_files()
        robots = next(f for f in files if "robots.txt" in str(f.path))
        assert "User-agent" in robots.content
        assert "Disallow" in robots.content

    def test_sitemap_has_xml_structure(self, basic_stack: StackSpec, tmp_path: Path) -> None:
        ctx = GeneratorContext(
            domain_spec=basic_stack,
            output_dir=tmp_path,
            dry_run=True,
            project_spec=ProjectSpec(name="test-project"),
        )
        gen = RobotsGenerator(ctx)
        files = gen.generate_files()
        sitemap = next(f for f in files if "sitemap.xml" in str(f.path))
        assert "<?xml" in sitemap.content
        assert "<urlset" in sitemap.content
        assert "<loc>" in sitemap.content
