"""
Supreme 2 MAX — MCP Prompts

Pre-defined prompt templates exposed via ``@mcp.prompt()`` decorators.
These guide LLMs on how to use Supreme 2 MAX effectively for common
security workflows.

Prompts
~~~~~~~
* ``security_scan_workflow``      — complete first-time scan workflow
* ``pr_security_check``           — quick security check for PR review
* ``false_positive_analysis``     — interpret and filter scan findings
* ``vulnerability_remediation``   — fix common security vulnerabilities
"""

from __future__ import annotations

from typing import Any, Dict, List

from supreme_max.mcp_server._server import mcp


# ---------------------------------------------------------------------------
# 1) security_scan_workflow
# ---------------------------------------------------------------------------

@mcp.prompt()
async def security_scan_workflow() -> str:
    """Complete workflow for first-time security scanning"""
    return """
# Security Scan Workflow

This workflow guides you through a complete security scan of a project.

## Steps:

1. Analyze Project Structure
   - Use: analyze_project(project_path)
   - This identifies languages, frameworks, and recommends optimal scanners

2. Review Recommendations
   - Check recommended_scanners list
   - Verify scan_time_estimate is acceptable

3. Run Security Scan
   - Use: run_security_scan(project_path, scanners=[recommended])
   - Mode: "full" for first scan
   - Save the returned scan_id

4. Analyze Findings
   - Use: analyze_findings(scan_id, fp_filter_level="moderate")
   - Review likely_false_positives count
   - Focus on critical_issues (top 10)

5. Generate Report
   - Use: generate_report(scan_id)
   - Report saved as JSON in ~/.supreme2l/reports/

6. Present Results
   - Show summary statistics
   - Highlight critical issues requiring immediate attention
   - Provide remediation suggestions
    """


# ---------------------------------------------------------------------------
# 2) pr_security_check
# ---------------------------------------------------------------------------

@mcp.prompt()
async def pr_security_check() -> str:
    """Quick security check for Pull Request review"""
    return """
# PR Security Check Workflow

Fast security check for changed files in Pull Request.

## Steps:

1. Run Quick Scan
   - Use: run_security_scan(project_path, mode="quick")
   - Mode "quick" scans only git diff (10x faster)
   - Automatically detects changed files

2. Filter Critical Issues
   - Use: get_scan_results(scan_id="latest", filters={"severity": ["CRITICAL", "HIGH"]})
   - Focus only on high-severity issues

3. Analyze Context
   - Use: analyze_findings(scan_id, fp_filter_level="conservative")
   - Conservative mode for PR (fewer false positives filtered)

4. Report to Developer
   - List issues found in changed files
   - Provide file:line locations
   - Suggest fixes for each issue

## Typical Response:
"I found 2 issues in your changes:
- CRITICAL: SQL injection in user.py:42
- HIGH: XSS vulnerability in template.html:15"
    """


# ---------------------------------------------------------------------------
# 3) false_positive_analysis
# ---------------------------------------------------------------------------

@mcp.prompt()
async def false_positive_analysis() -> str:
    """Guide on interpreting and filtering scan findings"""
    return """
# False Positive Analysis Guide

How to interpret scan results and distinguish real issues from false positives.

## Understanding analyze_findings Output:

1. likely_false_positive Field
   - true: Issue is probably safe (context suggests FP)
   - false: Issue needs attention

2. fp_reason Examples
   - "In test file" - Lower priority
   - "Uses parameterized query" - SQL injection unlikely
   - "Within SecureString wrapper" - Credential properly protected
   - "In docstring" - Documentation, not real code

3. confidence Score (0.0-1.0)
   - > 0.8: High confidence in assessment
   - 0.5-0.8: Medium confidence, review recommended
   - < 0.5: Low confidence, manual verification needed

4. priority_score
   - Combines severity + exploitability + impact
   - Higher score = more urgent

## Recommendations:
- Focus on critical_issues list first (top 10 highest priority)
- Review issues with likely_false_positive=false and confidence > 0.7
- Test files can often be ignored (reduced severity)
- Security wrappers (Fernet, SecureString) indicate proper handling
    """


# ---------------------------------------------------------------------------
# 4) vulnerability_remediation
# ---------------------------------------------------------------------------

@mcp.prompt()
async def vulnerability_remediation() -> str:
    """Patterns for fixing common security vulnerabilities"""
    return """
# Vulnerability Remediation Guide

Common patterns for fixing security issues found by Supreme 2 MAX.

## SQL Injection Fix:
Bad:
```python
query = f"SELECT * FROM users WHERE id ={user_id}"
cursor.execute(query)
```
Good:
```python
query = "SELECT * FROM users WHERE id = ?"
cursor.execute(query, (user_id,))
```

## XSS Prevention:
Bad:
```javascript
element.innerHTML = userInput;
```
Good:
```javascript
element.textContent = userInput;
// or use DOMPurify library
```

## Hardcoded Secrets:
Bad:
```python
API_KEY = "sk-abc123..."
```
Good:
```python
import os
API_KEY = os.getenv("API_KEY")
```

## Path Traversal:
Bad:
```python
filepath = os.path.join(base_dir, user_input)
```
Good:
```python
filepath = Path(base_dir) / user_input
filepath = filepath.resolve()
if not filepath.is_relative_to(base_dir):
    raise SecurityError("Invalid path")
```

## After Fixing:
- Run incremental scan: run_security_scan(mode="incremental")
- Verify issue is resolved
- Commit with reference to scan_id
    """


# ---------------------------------------------------------------------------
# Prompt registry — backward-compatible metadata export
# ---------------------------------------------------------------------------

PROMPT_REGISTRY: List[Dict[str, Any]] = [
    {
        "name": "security_scan_workflow",
        "description": "Complete workflow for first-time security scanning",
        "handler": security_scan_workflow,
    },
    {
        "name": "pr_security_check",
        "description": "Quick security check for Pull Request review",
        "handler": pr_security_check,
    },
    {
        "name": "false_positive_analysis",
        "description": "Guide on interpreting and filtering scan findings",
        "handler": false_positive_analysis,
    },
    {
        "name": "vulnerability_remediation",
        "description": "Patterns for fixing common security vulnerabilities",
        "handler": vulnerability_remediation,
    },
]
