"""
OSINT Analyze Tool - LLM-powered intelligence analysis

Provides artifact extraction and LLM-powered content analysis.
"""

from typing import Any, Optional

from groknroll.osint.artifact_extractor import ArtifactExtractor
from groknroll.osint.intelligence_analyzer import IntelligenceAnalyzer
from groknroll.tools.base_tool import BaseTool


class OsintAnalyzeTool(BaseTool):
    """
    Intelligence analysis tool with artifact extraction and LLM analysis.

    Extracts intelligence artifacts (emails, crypto addresses, domains, etc.)
    and optionally performs LLM-powered content analysis.

    Usage:
        tool = OsintAnalyzeTool()
        results = await tool.execute(content="...", extract_artifacts=True)
    """

    def __init__(
        self,
        backend: str = "anthropic",
        model: str = "claude-sonnet-4-20250514",
    ):
        """
        Initialize OSINT analyze tool.

        Args:
            backend: LLM backend ('anthropic', 'openai', 'google')
            model: LLM model identifier
        """
        self.backend = backend
        self.model = model
        self._extractor: Optional[ArtifactExtractor] = None
        self._analyzer: Optional[IntelligenceAnalyzer] = None

    @property
    def name(self) -> str:
        return "osint_analyze"

    @property
    def description(self) -> str:
        return "Extract artifacts and analyze intelligence from content"

    @property
    def extractor(self) -> ArtifactExtractor:
        """Get or create ArtifactExtractor."""
        if self._extractor is None:
            self._extractor = ArtifactExtractor()
        return self._extractor

    @property
    def analyzer(self) -> IntelligenceAnalyzer:
        """Get or create IntelligenceAnalyzer."""
        if self._analyzer is None:
            self._analyzer = IntelligenceAnalyzer(self.backend, self.model)
        return self._analyzer

    async def execute(
        self,
        content: str,
        source_url: str = "",
        extract_artifacts: bool = True,
        llm_analysis: bool = False,
        query: str = "",
        **kwargs,
    ) -> dict:
        """
        Analyze content for intelligence.

        Args:
            content: Text content to analyze
            source_url: Source URL for attribution
            extract_artifacts: If True, extract artifacts (emails, crypto, etc.)
            llm_analysis: If True, perform LLM-powered analysis
            query: Investigation query (required if llm_analysis=True)

        Returns:
            Dictionary with artifacts and/or analysis results
        """
        result: dict[str, Any] = {
            "content_length": len(content),
            "source_url": source_url,
        }

        # Extract artifacts
        if extract_artifacts:
            artifacts = self.extractor.extract_all(content, source_url)
            result["artifacts"] = [a.to_dict() for a in artifacts]
            result["artifact_summary"] = self.extractor.extract_summary(content, source_url)

        # LLM analysis
        if llm_analysis:
            if not query:
                raise ValueError("query parameter required for LLM analysis")

            # Create mock scraped content for analyzer
            from groknroll.osint.content_scraper import ScrapedContent

            scraped = ScrapedContent(
                url=source_url,
                title="",
                content=content,
                success=True,
            )

            artifact_dicts = result.get("artifacts", [])
            report = self.analyzer.analyze_content([scraped], query, artifact_dicts)
            result["analysis"] = report.to_dict()

        return result

    async def extract_only(
        self,
        content: str,
        source_url: str = "",
        artifact_type: Optional[str] = None,
    ) -> list[dict]:
        """
        Extract artifacts from content.

        Args:
            content: Text content to analyze
            source_url: Source URL for attribution
            artifact_type: Optional specific type to extract

        Returns:
            List of artifact dictionaries
        """
        if artifact_type:
            artifacts = self.extractor.extract_by_type(content, artifact_type, source_url)
        else:
            artifacts = self.extractor.extract_all(content, source_url)

        return [a.to_dict() for a in artifacts]

    async def refine_query(self, query: str) -> str:
        """
        Use LLM to refine a search query.

        Args:
            query: Original search query

        Returns:
            Refined query optimized for dark web search
        """
        return self.analyzer.refine_query(query)

    def validate_params(self, **kwargs) -> dict[str, Any]:
        """Validate analyze parameters."""
        content = kwargs.get("content")
        if content is None:
            raise ValueError("content parameter is required")

        if not isinstance(content, str):
            raise ValueError("content must be a string")

        if len(content) > 100000:
            raise ValueError("content exceeds maximum length of 100000 characters")

        llm_analysis = kwargs.get("llm_analysis", False)
        if llm_analysis:
            query = kwargs.get("query")
            if not query:
                raise ValueError("query parameter required when llm_analysis=True")

        return kwargs

    def get_supported_artifact_types(self) -> list[str]:
        """Get list of supported artifact types."""
        return self.extractor.get_supported_types()

    def check_status(self) -> dict[str, Any]:
        """Check tool status."""
        return {
            "backend": self.backend,
            "model": self.model,
            "artifact_types": self.get_supported_artifact_types(),
        }
