import logging
import json
from datetime import datetime

from agents import Agent, Runner, AgentOutputSchema

from models import (
    VulnerabilityAnalysis,
    RemediationPlans,
    SecurityReport,
    RiskLevel,
)

logger = logging.getLogger(__name__)


class ReportGeneratorAgent:
    """
    Agent that synthesizes vulnerability analysis and remediation plans
    into a comprehensive, executive-friendly security report.

    This agent:
    - Creates executive summary
    - Generates remediation roadmap with timelines
    - Highlights critical immediate actions
    - Provides implementation priority order
    - Calculates overall security posture
    - Recommends rescan frequency
    """

    INSTRUCTIONS = """
You are a security report writer creating actionable reports from vulnerability analysis and remediation plans.

Provide:
1. Executive summary and key findings
2. Vulnerabilities summary (counts by severity)
3. Critical issues list
4. Remediation roadmap (markdown format)
5. immediate_actions (list of strings - do today/this week)
6. weekly_actions (list of strings - do within 1-2 weeks)
7. monthly_actions (list of strings - do within a month)
8. Effort estimation and implementation priority
9. Next steps and rescan frequency
10. Overall risk level
11. Detailed findings (markdown)

Keep action items concise. Focus on business impact, practical commands, and CVE details.
"""

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

    def _create_agent(self) -> Agent:
        """Create the report generator agent with structured outputs."""
        return Agent(
            name="ReportGenerator",
            instructions=self.INSTRUCTIONS,
            model=self.model,
            output_type=AgentOutputSchema(SecurityReport, strict_json_schema=False),
        )

    async def generate_report(
        self,
        image_name: str,
        analysis: VulnerabilityAnalysis,
        remediation_plans: RemediationPlans,
    ) -> SecurityReport:
        """
        Generate comprehensive security report from analysis and remediation data.

        Args:
            image_name: Docker image that was scanned
            analysis: VulnerabilityAnalysis results
            remediation_plans: RemediationPlans generated by advisor

        Returns:
            SecurityReport with executive summary and action plan
        """
        logger.info(f"Generating security report for {image_name}")

        analysis_json = analysis.model_dump_json(indent=2)
        plans_json = remediation_plans.model_dump_json(indent=2)

        prompt = f"""
Security report for Docker image: {image_name}

VULNERABILITY ANALYSIS:
{analysis_json}

REMEDIATION PLANS:
{plans_json}

Create report with all required fields including separate immediate_actions, weekly_actions, and monthly_actions lists.
"""

        try:
            result = await Runner.run(self.agent, prompt)
            report = result.final_output
            logger.info(f"Report generated: Risk level = {report.overall_risk_level}")
            return report

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

    @staticmethod
    def format_report_markdown(report: SecurityReport) -> str:
        timestamp = report.scan_timestamp or datetime.now().isoformat()

        markdown = f"""# Security Vulnerability Report

**Image:** {report.image_name}
**Scan Date:** {timestamp}
**Overall Risk Level:** **{report.overall_risk_level.value}**

---

## Executive Summary

{report.executive_summary}

### Key Findings

{chr(10).join(f"- {finding}" for finding in report.key_findings)}

---

## Vulnerability Summary

| Severity | Count |
|----------|-------|
"""

        for severity, count in report.vulnerabilities_summary.items():
            markdown += f"| {severity} | {count} |\n"

        markdown += f"""
---

## Critical Issues (Immediate Action Required)

{chr(10).join(f"- {issue}" for issue in report.critical_issues) if report.critical_issues else "None"}

---

## Remediation Roadmap

### Immediate Actions (Today/This Week)

{chr(10).join(f"- {action}" for action in report.immediate_actions) if report.immediate_actions else "No immediate critical actions"}

### Weekly Actions (Within 1-2 Weeks)

{chr(10).join(f"- {action}" for action in report.weekly_actions) if report.weekly_actions else "No weekly actions"}

### Monthly Actions (Within a Month)

{chr(10).join(f"- {action}" for action in report.monthly_actions) if report.monthly_actions else "No monthly actions"}

---

## Implementation Plan

**Total Estimated Effort:** {report.estimated_total_effort_hours:.1f} hours

**Priority Order:**

{chr(10).join(f"{i+1}. {item}" for i, item in enumerate(report.implementation_priority))}

---

## Next Steps

{chr(10).join(f"- {step}" for step in report.next_steps)}

**Recommended Rescan Interval:** Every {report.rescan_recommendation_days} days

---

## Detailed Technical Findings

{report.detailed_findings}

---

*Report generated by Security Vulnerability Scanner & Remediation Advisor*
"""

        return markdown
