from dotenv import load_dotenv
import os
from typing import Optional


load_dotenv()


# Lazy-load API key to allow scan-only mode without API key
def get_openai_api_key() -> str:
    """
    Get OpenAI API key, raising error only when AI features are needed.
    
    Returns:
        str: The OpenAI API key from environment variables
        
    Raises:
        EnvironmentError: If OPENAI_API_KEY is not set
    """
    api_key: Optional[str] = os.getenv("OPENAI_API_KEY", "")
    if not api_key:
        error_message = """
[ERROR] No OpenAI API Key provided.

You can fix this by setting the `OPENAI_API_KEY` in one of the following ways:

- PowerShell (Windows):
    $env:OPENAI_API_KEY = "your-secret-key"

- Command Prompt (CMD on Windows):
    set OPENAI_API_KEY=your-secret-key

- Bash/Zsh (Linux/macOS):
    export OPENAI_API_KEY="your-secret-key"

- Or create a `.env` file with:
    OPENAI_API_KEY=your-secret-key


[SECURITY] Reminder: Never hardcode your API key in public code or repositories. It is necessary to use DockSec AI features.

Note: You can use scan-only mode (--scan-only) without an API key.
"""
        raise EnvironmentError(error_message.strip())
    return api_key

# Set environment variable if key exists (for backward compatibility)
# But don't raise error if missing - let get_openai_api_key() handle that
OPENAI_API_KEY: str = os.getenv("OPENAI_API_KEY", "")
if OPENAI_API_KEY:
    os.environ["OPENAI_API_KEY"] = OPENAI_API_KEY

BASE_DIR: str = os.path.abspath(os.path.dirname(__file__))

# Results directory configuration
# Priority: 1. Environment variable, 2. DockSec installation directory (default)
# Users can customize by setting: export DOCKSEC_RESULTS_DIR=/custom/path
RESULTS_DIR: str = os.getenv("DOCKSEC_RESULTS_DIR", os.path.join(BASE_DIR, "results"))

# Create results directory if it doesn't exist
os.makedirs(RESULTS_DIR, exist_ok=True)



from langchain_core.prompts import PromptTemplate

docker_agent_template = """
    you are an AI agent that is tasked with analyzing a Dockerfile for security vulnerabilities.
    The Dockerfile is provided to you as a string.
    You need to analyze the Dockerfile and provide a report on the security vulnerabilities present in the Dockerfile.
    You need to identify the vulnerabilities and provide a detailed report on the security risks associated with each vulnerability.

    Output format should be json as below:

    {{
        "vulnerabilities": ["vulnerability1", "vulnerability2", "vulnerability3"],
        "best_practices": ["best practice1", "best practice2", "best practice3"],
        "SecurityRisks": ["security risk1", "security risk2", "security risk3"],
        "ExposedCredentials": ["credential1", "credential2", "credential3"],
        "remediation": ["remediation1", "remediation2", "remediation3"]
    }}


    Docker File to analyze: \n {filecontent}

"""

docker_agent_prompt = PromptTemplate(
    input_variables=["filecontent"],
    template=docker_agent_template
)

docker_score_template = """
You are a Docker Security Expert with extensive knowledge of container security best practices, vulnerabilities, and compliance standards. You will be provided with the security scan results from tools such as Trivy, Clair, or Docker Bench for Security. Your task is to analyze these results and assign a security score between 1 and 100 based on the severity, number, and impact of detected vulnerabilities or misconfigurations.

    ### Scoring Criteria:
    - Base the score on factors including:
    - **Vulnerability Severity**: Critical (high impact), High, Medium, Low.
    - **Misconfigurations**: Privileged containers, exposed sensitive information, missing security policies.
    - **CVE Scores**: Common Vulnerabilities and Exposures (CVEs) detected in the image.
    - **Compliance Violations**: CIS Docker Benchmark compliance, runtime security policies.
    - **Attack Surface Exposure**: Open ports, excessive privileges, unnecessary packages.
    - **Dependency Risks**: Outdated base images, unpatched libraries.

    ### Output Format:
    Your response must be a JSON object with a single key-value pair:

    {{
        "score": 90
    }}
    
    Results:
    {results}



"""

docker_score_prompt = PromptTemplate(
    input_variables=["results"],
    template=docker_score_template
)

# report_template.py

html_template = """
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Docker Security Report</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            line-height: 1.6;
            color: #333;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }
        
        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            border-radius: 15px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.1);
            overflow: hidden;
        }
        
        .header {
            background: linear-gradient(135deg, #2c3e50 0%, #3498db 100%);
            color: white;
            padding: 40px;
            text-align: center;
            position: relative;
            overflow: hidden;
        }
        
        .header::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><defs><pattern id="grain" width="100" height="100" patternUnits="userSpaceOnUse"><circle cx="25" cy="25" r="1" fill="rgba(255,255,255,0.1)"/><circle cx="75" cy="75" r="1" fill="rgba(255,255,255,0.1)"/><circle cx="50" cy="10" r="0.5" fill="rgba(255,255,255,0.1)"/></pattern></defs><rect width="100" height="100" fill="url(%23grain)"/></svg>');
            opacity: 0.3;
        }
        
        .header h1 {
            font-size: 2.5em;
            margin-bottom: 10px;
            position: relative;
            z-index: 1;
        }
        
        .header p {
            font-size: 1.2em;
            opacity: 0.9;
            position: relative;
            z-index: 1;
        }
        
        .content {
            padding: 40px;
        }
        
        .section {
            margin-bottom: 40px;
            background: #f8f9ff;
            border-radius: 12px;
            padding: 30px;
            border-left: 5px solid #3498db;
            transition: transform 0.3s ease, box-shadow 0.3s ease;
        }
        
        .section:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 25px rgba(0,0,0,0.1);
        }
        
        .section h2 {
            color: #2c3e50;
            margin-bottom: 20px;
            font-size: 1.8em;
            position: relative;
            padding-bottom: 10px;
        }
        
        .section h2::after {
            content: '';
            position: absolute;
            bottom: 0;
            left: 0;
            width: 50px;
            height: 3px;
            background: linear-gradient(90deg, #3498db, #667eea);
            border-radius: 2px;
        }
        
        .info-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            gap: 20px;
            margin-bottom: 20px;
        }
        
        .info-item {
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
            border: 1px solid #e1e8ed;
        }
        
        .info-label {
            font-weight: 600;
            color: #2c3e50;
            margin-bottom: 8px;
            font-size: 0.9em;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }
        
        .info-value {
            color: #555;
            font-size: 1.1em;
            word-break: break-all;
        }
        
        .severity-stats {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
            gap: 15px;
            margin: 20px 0;
        }
        
        .severity-item {
            background: white;
            padding: 20px;
            border-radius: 10px;
            text-align: center;
            box-shadow: 0 4px 15px rgba(0,0,0,0.08);
            transition: transform 0.3s ease;
        }
        
        .severity-item:hover {
            transform: translateY(-3px);
        }
        
        .severity-critical {
            border-left: 5px solid #e74c3c;
        }
        
        .severity-high {
            border-left: 5px solid #f39c12;
        }
        
        .severity-medium {
            border-left: 5px solid #f1c40f;
        }
        
        .severity-low {
            border-left: 5px solid #27ae60;
        }
        
        .severity-count {
            font-size: 2em;
            font-weight: bold;
            margin-bottom: 5px;
        }
        
        .severity-label {
            font-size: 0.9em;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            opacity: 0.8;
        }
        
        .vulnerability-table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
            background: white;
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
        }
        
        .vulnerability-table th {
            background: linear-gradient(135deg, #2c3e50 0%, #3498db 100%);
            color: white;
            padding: 15px 12px;
            text-align: left;
            font-weight: 600;
            text-transform: uppercase;
            font-size: 0.85em;
            letter-spacing: 0.5px;
        }
        
        .vulnerability-table td {
            padding: 12px;
            border-bottom: 1px solid #e1e8ed;
            vertical-align: top;
        }
        
        .vulnerability-table tr:nth-child(even) {
            background-color: #f8f9ff;
        }
        
        .vulnerability-table tr:hover {
            background-color: #e3f2fd;
            transition: background-color 0.3s ease;
        }
        
        .severity-badge {
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 0.8em;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }
        
        .badge-critical {
            background: #fee;
            color: #e74c3c;
            border: 1px solid #e74c3c;
        }
        
        .badge-high {
            background: #fef5e7;
            color: #f39c12;
            border: 1px solid #f39c12;
        }
        
        .badge-medium {
            background: #fffbf0;
            color: #f1c40f;
            border: 1px solid #f1c40f;
        }
        
        .badge-low {
            background: #f0f9ff;
            color: #27ae60;
            border: 1px solid #27ae60;
        }
        
        .status-badge {
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 0.75em;
            font-weight: 500;
        }
        
        .status-fixed {
            background: #d4edda;
            color: #155724;
        }
        
        .status-affected {
            background: #f8d7da;
            color: #721c24;
        }
        
        .no-issues {
            text-align: center;
            padding: 40px;
            color: #27ae60;
            font-size: 1.2em;
            font-weight: 500;
        }
        
        .no-issues::before {
            content: '[OK]';
            display: block;
            font-size: 2em;
            margin-bottom: 10px;
            color: #27ae60;
        }
        
        .footer {
            text-align: center;
            padding: 30px;
            background: #f8f9fa;
            color: #666;
            font-size: 0.9em;
        }
        
        .score-container {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 30px;
            border-radius: 12px;
            text-align: center;
            margin-bottom: 20px;
        }
        
        .score-value {
            font-size: 4em;
            font-weight: bold;
            margin: 10px 0;
            text-shadow: 0 2px 4px rgba(0,0,0,0.3);
        }
        
        .score-label {
            font-size: 1.2em;
            opacity: 0.9;
            text-transform: uppercase;
            letter-spacing: 1px;
        }
        
        .config-issues {
            margin-top: 20px;
        }
        
        .config-category {
            margin-bottom: 20px;
        }
        
        .config-category h4 {
            color: #2c3e50;
            margin-bottom: 10px;
            font-size: 1.1em;
        }
        
        .config-list {
            list-style: none;
            padding: 0;
        }
        
        .config-list li {
            background: white;
            margin-bottom: 8px;
            padding: 12px 15px;
            border-radius: 6px;
            border-left: 4px solid #e74c3c;
            box-shadow: 0 2px 5px rgba(0,0,0,0.05);
        }
        
        .config-list.medium li {
            border-left-color: #f39c12;
        }
        
        .config-list.low li {
            border-left-color: #f1c40f;
        }
        
        @media (max-width: 768px) {
            .container {
                margin: 10px;
                border-radius: 8px;
            }
            
            .header {
                padding: 20px;
            }
            
            .header h1 {
                font-size: 2em;
            }
            
            .content {
                padding: 20px;
            }
            
            .section {
                padding: 20px;
            }
            
            .info-grid {
                grid-template-columns: 1fr;
            }
            
            .vulnerability-table {
                font-size: 0.85em;
            }
            
            .vulnerability-table th,
            .vulnerability-table td {
                padding: 8px 6px;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>Docker Security Report</h1>
            <p>{{SCAN_MODE_TITLE}}</p>
        </div>
        
        <div class="content">
            <!-- Scan Information Section -->
            <div class="section">
                <h2>Scan Information</h2>
                <div class="info-grid">
                    <div class="info-item">
                        <div class="info-label">Image Name</div>
                        <div class="info-value">{{IMAGE_NAME}}</div>
                    </div>
                    <div class="info-item">
                        <div class="info-label">Scan Mode</div>
                        <div class="info-value">{{SCAN_MODE}}</div>
                    </div>
                    <div class="info-item">
                        <div class="info-label">Dockerfile Path</div>
                        <div class="info-value">{{DOCKERFILE_PATH}}</div>
                    </div>
                    <div class="info-item">
                        <div class="info-label">Scan Date</div>
                        <div class="info-value">{{SCAN_DATE}}</div>
                    </div>
                    <div class="info-item">
                        <div class="info-label">Analysis Score</div>
                        <div class="info-value">{{ANALYSIS_SCORE}}</div>
                    </div>
                </div>
            </div>

            <!-- Security Score Section -->
            {{SECURITY_SCORE_SECTION}}

            <!-- Image Information Section -->
            {{IMAGE_INFO_SECTION}}

            <!-- Configuration Analysis Section -->
            {{CONFIG_ANALYSIS_SECTION}}

            <!-- Dockerfile Scan Results Section -->
            {{DOCKERFILE_SECTION}}

            <!-- Vulnerability Summary Section -->
            <div class="section">
                <h2>Vulnerability Summary</h2>
                {{VULNERABILITY_SUMMARY}}
            </div>

            <!-- Detailed Vulnerabilities Section -->
            {{DETAILED_VULNERABILITIES_SECTION}}
        </div>
        
        <div class="footer">
            <p>Generated by docksec on {{SCAN_DATE}}</p>
        </div>
    </div>
</body>
</html>

"""
