"""KREP SEO reporting agent."""

from __future__ import annotations

from datetime import datetime
from typing import Any

from kiessclaw.core.agent import BaseAgent
from kiessclaw.core.memory import MemoryEngine


class KiessReporterAgent(BaseAgent):
    """Create SEO reporting summaries from crawl history."""

    codename = "KREP"
    name = "KiessReporter"
    description = "Weekly SEO reports and trend summaries"

    def __init__(self, config: dict[str, Any], memory: MemoryEngine):
        """Initialize reporter agent."""
        super().__init__(config, memory)

    def run(self, task: str, **kwargs: Any) -> str:
        """Execute reporting tasks."""
        self.update_status("running", task)
        try:
            if task == "report" or "report" in task.lower():
                return self._weekly_report()
            return self.think(task).content
        finally:
            self.update_status("idle")

    def _weekly_report(self) -> str:
        """Generate a markdown SEO audit trend report."""
        audits = self.memory.load_data("seo_audits")
        if not audits:
            return "No SEO audits available."

        recent = audits[-20:]
        avg_score = sum(item.get("technical_score", 0) for item in recent) / len(recent)
        low_domains = [item.get("domain") for item in recent if item.get("technical_score", 100) < 60]

        report = (
            f"# KREP SEO Report\n"
            f"Generated: {datetime.now().isoformat()}\n\n"
            f"- Audits analyzed: {len(recent)}\n"
            f"- Average technical score: {avg_score:.1f}\n"
            f"- Low-score domains (<60): {len(low_domains)}\n"
        )
        if low_domains:
            report += "\n## Domains Needing Recovery\n" + "\n".join(f"- {domain}" for domain in low_domains if domain)
        return report

