import logging
import json
from typing import List

from agents import Agent, Runner

from models import (
    Vulnerability,
    VulnerabilityAnalysis,
    AnalyzedVulnerability,
    SeverityLevel,
    ExploitabilityLevel,
)

logger = logging.getLogger(__name__)


class VulnerabilityAnalyzerAgent:
    """
    Agent that analyzes raw vulnerabilities from Trivy scan.
    Structures, prioritizes, and groups vulnerabilities for deeper analysis.

    This agent:
    - Analyzes each vulnerability's context
    - Groups vulnerabilities by component
    - Assigns risk scores and exploitability
    - Prioritizes by business impact
    - Identifies critical vs nice-to-fix items
    """

    INSTRUCTIONS = """
You are a security vulnerability analyst reviewing Trivy scan results.

Analyze and prioritize vulnerabilities by:
1. Business impact and exploitability
2. Package grouping
3. False positive identification
4. Risk scores (0-100): CRITICAL+exploit=90-100, CRITICAL=75-89, HIGH+exploit=70-79, HIGH=50-69, MEDIUM=20-49, LOW=10-19

Provide structured analysis with clear reasoning. Focus on business impact.
"""

    def __init__(self, model: str = "gpt-4o-mini"):
        self.model = model
        self.agent = self._create_agent()
        logger.info("VulnerabilityAnalyzerAgent initialized")

    def _create_agent(self) -> Agent:
        """Create the analyzer agent with structured outputs."""
        return Agent(
            name="VulnerabilityAnalyzer",
            instructions=self.INSTRUCTIONS,
            model=self.model,
            output_type=VulnerabilityAnalysis,
        )

    async def analyze(self, vulnerabilities: List[Vulnerability]) -> VulnerabilityAnalysis:
        """
        Analyze list of vulnerabilities and return structured analysis.

        Args:
            vulnerabilities: List of Vulnerability objects from scanner

        Returns:
            VulnerabilityAnalysis with prioritized and analyzed vulnerabilities
        """
        if not vulnerabilities:
            return self._create_empty_analysis()

        logger.info(f"Analyzing {len(vulnerabilities)} vulnerabilities")

        vuln_json = json.dumps([v.model_dump() for v in vulnerabilities], indent=2)

        prompt = f"""
Vulnerabilities from Docker image scan:

{vuln_json}

Analyze and prioritize by business impact and risk.
"""

        try:
            result = await Runner.run(self.agent, prompt)
            analysis = result.final_output
            logger.info(f"Analysis complete: {analysis.critical_count} critical issues found")
            return analysis

        except Exception as e:
            logger.error(f"Analysis failed: {str(e)}")
            raise

    def _create_empty_analysis(self) -> VulnerabilityAnalysis:
        """Create empty analysis when no vulnerabilities found."""
        return VulnerabilityAnalysis(
            total_found=0,
            critical_count=0,
            high_count=0,
            medium_count=0,
            low_count=0,
            analysis=[],
            summary="No vulnerabilities found in the image.",
            key_risks=[],
        )
