"""KRAWL SEO crawler agent."""

from __future__ import annotations

import logging
from typing import Any

from kiessclaw.core.agent import BaseAgent
from kiessclaw.core.memory import MemoryEngine
from kiessclaw.seo.skills.crawl import CrawlSkill

logger = logging.getLogger(__name__)


class KiessCrawlerAgent(BaseAgent):
    """Run technical SEO crawls and produce audit outputs."""

    codename = "KRAWL"
    name = "KiessCrawler"
    description = "Site crawl, technical SEO audit, and score computation"

    def __init__(self, config: dict[str, Any], memory: MemoryEngine):
        """Initialize crawler dependencies."""
        super().__init__(config, memory)
        self.crawl_skill = CrawlSkill(config)

    def run(self, task: str, **kwargs: Any) -> Any:
        """Execute crawler tasks."""
        self.update_status("running", task)
        try:
            if task == "audit" or "audit" in task.lower():
                return self._handle_audit(**kwargs)
            return self._handle_natural_language(task)
        except Exception as exc:  # noqa: BLE001
            logger.error("[KRAWL] Error: %s", exc)
            self.update_status("error", task)
            return f"Error: {exc}"
        finally:
            self.update_status("idle")

    def audit(self, url: str, max_pages: int | None = None) -> dict[str, Any]:
        """Run raw audit and return structured data."""
        return self.crawl_skill.audit_site(url, max_pages=max_pages)

    def _handle_audit(
        self,
        url: str | None = None,
        max_pages: int | None = None,
        return_data: bool = False,
        **_: Any,
    ) -> Any:
        """Run crawl audit and save report to workspace data."""
        if not url:
            return "Error: url is required for audit"

        audit_result = self.audit(url=url, max_pages=max_pages)
        self.memory.append_data("seo_audits", audit_result)

        self.memory.log(
            "krawl",
            f"**SEO Audit**\n"
            f"- Domain: {audit_result['domain']}\n"
            f"- Score: {audit_result['technical_score']}\n"
            f"- Pages: {audit_result['pages_crawled']}\n"
            f"- Broken links: {len(audit_result['broken_links'])}",
        )
        if return_data:
            return audit_result
        return self._format_audit(audit_result)

    def _handle_natural_language(self, task: str) -> str:
        """Handle natural language requests through the LLM route."""
        context = "SEO audits available in data collection: seo_audits."
        response = self.think(task, context=context)
        return response.content

    def _format_audit(self, result: dict[str, Any]) -> str:
        """Render a human-readable audit summary."""
        return (
            f"**KRAWL Audit**\n\n"
            f"- Domain: {result['domain']}\n"
            f"- Technical SEO Score: {result['technical_score']}/100\n"
            f"- Pages Crawled: {result['pages_crawled']}\n"
            f"- Missing Titles: {result['missing_title_pages']}\n"
            f"- Missing Meta Descriptions: {result['missing_meta_pages']}\n"
            f"- Broken Links: {len(result['broken_links'])}\n"
            f"- robots.txt: {'ok' if result['robots_ok'] else 'missing'}\n"
            f"- sitemap.xml: {'ok' if result['sitemap_ok'] else 'missing'}\n"
            f"- Owner Contact: {result.get('owner_contact') or 'not found'}"
        )

