# Path: scaffold/artisans/ignore/artisan.py
# -----------------------------------------

import requests
from pathlib import Path
from typing import List, Set

from ...core.artisan import BaseArtisan
from ...interfaces.base import ScaffoldResult, Artifact
from ...interfaces.requests import IgnoreRequest
from ...help_registry import register_artisan
from ...utils import atomic_write


@register_artisan("ignore")
class IgnoreArtisan(BaseArtisan[IgnoreRequest]):
    """
    =============================================================================
    == THE GATEKEEPER OF AVERSION (V-Ω-GITIGNORE-IO)                           ==
    =============================================================================
    LIF: 10,000,000,000

    Fetches and merges .gitignore templates from the gitignore.io API.
    """

    API_URL = "https://www.toptal.com/developers/gitignore/api"

    def execute(self, request: IgnoreRequest) -> ScaffoldResult:
        targets = [t.lower() for t in request.templates]
        self.logger.info(f"Communing with the Gatekeeper for: [cyan]{', '.join(targets)}[/cyan]")

        # 1. The Celestial Request
        try:
            api_query = ",".join(targets)
            response = requests.get(f"{self.API_URL}/{api_query}", timeout=10)
            response.raise_for_status()
            content = response.text
        except Exception as e:
            return self.failure(f"Celestial Communion Failed: {e}")

        # 2. The Gnostic Header
        header = (
            f"# Generated by Scaffold God-Engine\n"
            f"# Templates: {', '.join(targets)}\n"
            f"# -----------------------------------------------------------------------------\n"
        )
        final_content = header + content

        # 3. The Inscription
        target_path = self.project_root / ".gitignore"

        if request.append and target_path.exists():
            original = target_path.read_text(encoding='utf-8')
            # Deduplication Check (Naive)
            if f"# Templates: {', '.join(targets)}" in original:
                return self.success("These rules are already inscribed.")

            final_content = original + "\n\n" + final_content
            action = "appended"
        else:
            if target_path.exists():
                self.guarded_execution([target_path], request, context="ignore_overwrite")
            action = "created"

        atomic_write(target_path, final_content, self.logger, self.project_root)

        return self.success(
            f".gitignore {action} with rules for {', '.join(targets)}.",
            artifacts=[Artifact(path=target_path, type="file", action="modified")]
        )