"""Explanation and remediation tools — LLM-powered finding analysis.

Provides ``explain_finding`` and ``suggest_remediation`` tools that
use the LLM backbone to generate human-readable explanations and
actionable fix suggestions for discovered vulnerabilities.
"""

from __future__ import annotations

import logging
from typing import TYPE_CHECKING, Any

if TYPE_CHECKING:
    from ziran.infrastructure.llm.base import BaseLLMClient

logger = logging.getLogger(__name__)


async def explain_finding(
    llm_client: BaseLLMClient,
    *,
    finding: dict[str, Any],
) -> dict[str, Any]:
    """Generate a human-readable explanation of a security finding.

    Args:
        llm_client: LLM client for explanation generation.
        finding: Finding data (vector_id, category, severity, evidence, etc.).

    Returns:
        Explanation with risk assessment and impact analysis.
    """
    prompt = (
        "You are a cybersecurity expert analyzing an AI agent vulnerability finding.\n\n"
        f"Finding details:\n"
        f"- Vector: {finding.get('vector_name', finding.get('vector_id', 'unknown'))}\n"
        f"- Category: {finding.get('category', 'unknown')}\n"
        f"- Severity: {finding.get('severity', 'unknown')}\n"
        f"- OWASP Mapping: {finding.get('owasp', [])}\n"
        f"- Evidence: {finding.get('evidence_keys', [])}\n\n"
        "Provide:\n"
        "1. A clear explanation of what this vulnerability means\n"
        "2. The potential real-world impact\n"
        "3. How an attacker could exploit this\n"
        "4. Risk assessment (likelihood x impact)\n\n"
        "Be concise but thorough. Format as structured text."
    )

    try:
        response = await llm_client.complete(
            messages=[{"role": "user", "content": prompt}],
            temperature=0.3,
            max_tokens=1024,
        )
        return {
            "explanation": response.content,
            "vector_id": finding.get("vector_id", ""),
            "token_usage": {
                "prompt_tokens": response.prompt_tokens,
                "completion_tokens": response.completion_tokens,
                "total_tokens": response.total_tokens,
            },
        }
    except Exception as e:
        logger.warning("Finding explanation failed: %s", e)
        return {
            "explanation": f"Explanation generation failed: {e}",
            "vector_id": finding.get("vector_id", ""),
            "error": str(e),
        }


async def suggest_remediation(
    llm_client: BaseLLMClient,
    *,
    finding: dict[str, Any],
    framework: str = "unknown",
) -> dict[str, Any]:
    """Generate remediation suggestions for a security finding.

    Args:
        llm_client: LLM client for remediation generation.
        finding: Finding data.
        framework: Agent framework (langchain, crewai, etc.) for tailored advice.

    Returns:
        Remediation suggestions with code examples and guardrail configs.
    """
    prompt = (
        "You are a cybersecurity expert providing remediation advice for an AI agent vulnerability.\n\n"
        f"Finding details:\n"
        f"- Vector: {finding.get('vector_name', finding.get('vector_id', 'unknown'))}\n"
        f"- Category: {finding.get('category', 'unknown')}\n"
        f"- Severity: {finding.get('severity', 'unknown')}\n"
        f"- OWASP Mapping: {finding.get('owasp', [])}\n"
        f"- Agent Framework: {framework}\n\n"
        "Provide:\n"
        "1. Immediate mitigation steps\n"
        "2. Long-term fixes with code examples\n"
        "3. Guardrail configurations for the agent framework\n"
        "4. Testing recommendations to verify the fix\n\n"
        "Be specific and actionable. Include code snippets where helpful."
    )

    try:
        response = await llm_client.complete(
            messages=[{"role": "user", "content": prompt}],
            temperature=0.3,
            max_tokens=2048,
        )
        return {
            "remediation": response.content,
            "vector_id": finding.get("vector_id", ""),
            "framework": framework,
            "token_usage": {
                "prompt_tokens": response.prompt_tokens,
                "completion_tokens": response.completion_tokens,
                "total_tokens": response.total_tokens,
            },
        }
    except Exception as e:
        logger.warning("Remediation suggestion failed: %s", e)
        return {
            "remediation": f"Remediation generation failed: {e}",
            "vector_id": finding.get("vector_id", ""),
            "error": str(e),
        }
