"""KANA SEO analysis agent."""

from __future__ import annotations

from typing import Any

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


class KiessAnalystAgent(BaseAgent):
    """Analyze keyword opportunities and SERP intent/gaps."""

    codename = "KANA"
    name = "KiessAnalyst"
    description = "Keyword research, SERP analysis, and competitor gap detection"

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

    def run(self, task: str, **kwargs: Any) -> str:
        """Execute keyword and gap analysis tasks."""
        self.update_status("running", task)
        try:
            if task == "research" or "keyword" in task.lower():
                return self._keyword_research(kwargs.get("domain"), kwargs.get("topic"))
            if task == "gap" or "competitor" in task.lower():
                return self._competitor_gap(kwargs.get("domain"), kwargs.get("competitor"))
            return self.think(task).content
        finally:
            self.update_status("idle")

    def _keyword_research(self, domain: str | None, topic: str | None) -> str:
        """Generate lightweight keyword intent suggestions."""
        base = (topic or domain or "growth").replace("-", " ").strip()
        seeds = [base, f"{base} software", f"{base} services", f"{base} pricing"]
        lines = ["**KANA Keyword Research**", ""]
        for seed in seeds:
            intent = "commercial" if any(word in seed for word in ["pricing", "software", "services"]) else "informational"
            lines.append(f"- {seed}: intent={intent}")
        return "\n".join(lines)

    def _competitor_gap(self, domain: str | None, competitor: str | None) -> str:
        """Produce a deterministic competitor gap checklist."""
        return (
            "**KANA Competitor Gap**\n\n"
            f"- Target: {domain or 'unknown'}\n"
            f"- Competitor: {competitor or 'unknown'}\n"
            "- Gap checks: title tags, landing page depth, topical clusters, internal links"
        )

