"""PASTA Stage 5 — Vulnerability and Weakness Analysis prompt template."""

from threatsmith.frameworks.references.scanner_snippets import SCANNER_SNIPPETS
from threatsmith.frameworks.types import StageContext

STAGE_PROMPT = """\
You are a vulnerability analyst performing PASTA (Process for Attack Simulation \
and Threat Analysis) Stage 5 — Vulnerability and Weakness Analysis. Your task is \
to systematically identify, validate, score, and classify every exploitable \
vulnerability and design weakness in the application by combining automated \
scanner results with manual code analysis informed by the threat inventory from \
Stage 4. This stage transforms abstract threats into concrete, evidence-based \
vulnerability findings that drive attack modeling (Stage 6) and risk \
prioritization (Stage 7).

**CRITICAL REQUIREMENT: Every threat identified in Stage 4 must be traced to \
either a confirmed vulnerability, a validated design weakness, or an explicit \
determination that no exploitable weakness exists for that threat. Unexamined \
threats represent gaps in your analysis.**

Your task is to analyze the codebase in the current working directory and produce \
a comprehensive vulnerability analysis covering the five pillars below.

{prior_stages_section}

{scanner_section}

## ANALYSIS PILLARS

Your analysis must address each of the following five pillars. These correspond to \
required top-level sections in your output.

### 1. Scanner-Augmented Vulnerability Discovery

Leverage available automated security scanners to establish a baseline of known \
vulnerabilities, then correlate scanner findings with the threat inventory from \
Stage 4. Scanners find what pattern matching can detect; your job is to interpret \
what the findings mean in this application's context.

**If scanners are available (listed in the SCANNER INSTRUCTIONS section below), \
run them and integrate their results:**

- **Execute each available scanner** against the codebase using the provided \
commands. Parse and analyze all output.
- **Correlate scanner findings with Stage 4 threats:** For each scanner finding, \
identify which Stage 4 threat(s) it validates or provides evidence for. Scanner \
findings that do not map to any Stage 4 threat may indicate threats that were \
missed — flag these as newly discovered.
- **False positive assessment:** Use business context from Stage 1, technical \
scope from Stage 2, and application architecture from Stage 3 to evaluate each \
scanner finding. Classify findings as:
  - **Confirmed:** Evidence supports exploitability in this application's context
  - **Likely:** Pattern matches a known vulnerability class but requires manual \
verification of exploitability
  - **False positive:** Finding is not exploitable due to compensating controls, \
dead code, or context the scanner cannot evaluate — document the reasoning
- **Gap identification:** After processing scanner results, identify which Stage 4 \
threats have NO corresponding scanner findings. These gaps require manual code \
analysis in subsequent pillars.

**If no scanners are available:**
- Rely entirely on manual code analysis guided by the Stage 4 threat inventory.
- Note the absence of automated validation as a limitation in your findings.

### 2. Threat-to-Vulnerability Mapping with Threat Trees

Systematically trace each threat from Stage 4 through the codebase to determine \
whether exploitable vulnerabilities exist. Use threat trees to model the \
relationship between threats, weaknesses, and exploitation paths.

**For each significant threat from Stage 4:**

- **Root cause analysis:** Trace the threat to its technical root cause in the \
code. Is there a missing control, a flawed implementation, or an insecure default \
that makes this threat exploitable? Reference specific files, functions, and line \
numbers.

- **Threat tree construction:** Build a logical tree showing:
  - The threat goal (root node) — what the attacker achieves
  - The preconditions required (AND/OR decomposition)
  - The specific code-level weaknesses that enable each path
  - Existing controls that block or mitigate branches of the tree
  Use text-based tree notation (indented lists with AND/OR annotations) to document \
threat trees. Reserve Mermaid diagrams for the most critical or complex trees.

- **Exploitability assessment:** For each vulnerability path in the threat tree:
  - Can the weakness be triggered through an accessible entry point?
  - What input or interaction is required to exploit it?
  - Are there compensating controls that reduce or eliminate exploitability?
  - What is the attacker skill level required?

- **Vulnerability chain analysis:** Identify cases where multiple individually \
low-severity weaknesses combine into a high-severity exploitation path. Document \
how vulnerability A enables exploitation of vulnerability B, creating attack chains \
that are more dangerous than any individual finding.

### 3. Design Flaw Analysis

Examine the application for systemic design weaknesses that automated scanners \
cannot detect. Design flaws are architectural or logical deficiencies — they are \
not bugs in code but deficiencies in how the system was designed to handle security \
concerns.

- **Use case security review:** For each legitimate use case identified in \
Stage 3, examine:
  - Are security controls applied consistently across the use case's execution path?
  - Can the use case be subverted by manipulating sequence, timing, or state?
  - Are there assumptions about user behavior that an attacker would violate?
  - Does the use case handle error conditions without exposing security-sensitive \
information or entering an insecure state?

- **Abuse case development:** For each significant use case, construct at least \
one abuse case:
  - What happens if the use case is invoked with malicious intent?
  - What if legitimate parameters are pushed to extreme values?
  - What if the expected sequence of operations is reordered or repeated?
  - What if the use case is combined with another use case in unexpected ways?
  Document abuse cases as scenario narratives with preconditions, attack steps, \
and expected outcomes.

- **Trust boundary violation analysis:** Using the trust boundaries from Stage 3:
  - Is data validated or sanitized at every trust boundary crossing?
  - Are credentials and tokens verified at each boundary, or does the system rely \
on upstream validation?
  - Can an attacker bypass a trust boundary by accessing a component directly \
rather than through the expected entry point?

- **Security control gap analysis:** Identify missing security controls by \
comparing what the application implements against what its threat profile requires:
  - Authentication completeness: are all sensitive operations gated?
  - Authorization granularity: is access control applied at the right level?
  - Input validation coverage: are all entry points validated?
  - Logging adequacy: are security-relevant events logged for detection?
  - Cryptographic correctness: are cryptographic operations using appropriate \
algorithms, key sizes, and modes?

### 4. Vulnerability Scoring and Classification

Apply industry-standard scoring and classification to every confirmed vulnerability \
and design weakness. Consistent scoring enables rational prioritization in Stage 7.

**For each vulnerability, provide:**

- **CVSS 3.1 Base Score calculation** with the following vector components:
  - Attack Vector (AV): Network / Adjacent / Local / Physical
  - Attack Complexity (AC): Low / High
  - Privileges Required (PR): None / Low / High
  - User Interaction (UI): None / Required
  - Scope (S): Unchanged / Changed
  - Confidentiality Impact (C): None / Low / High
  - Integrity Impact (I): None / Low / High
  - Availability Impact (A): None / Low / High
  Document the full CVSS vector string (e.g., CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/\
C:H/I:H/A:H) and the resulting numeric score.

- **Severity rating:** Critical (9.0-10.0) / High (7.0-8.9) / Medium (4.0-6.9) \
/ Low (0.1-3.9) / Informational (0.0)

- **CWE classification:** Assign the most specific applicable Common Weakness \
Enumeration identifier (e.g., CWE-89: SQL Injection, CWE-79: Cross-site Scripting). \
If multiple CWEs apply, list all with the primary CWE first.

- **CVE cross-reference:** For vulnerabilities in third-party dependencies \
identified by scanners, include the CVE identifier(s) from scanner results. For \
application-specific vulnerabilities, note "No CVE — application-specific finding."

- **Environmental context adjustment:** Use deployment context from Stage 2 to \
note where the base score may shift:
  - Internal-only applications may have reduced Attack Vector impact
  - Applications with WAF or rate limiting may have increased Attack Complexity
  - Applications processing regulated data may warrant higher impact weighting
  Document adjustments as qualitative notes, not modified scores — leave formal \
environmental scoring to the risk assessment in Stage 7.

### 5. Impact and Exposure Assessment

Assess the concrete impact of each vulnerability on the application's systems, \
data, and operations. This pillar connects technical findings to business \
consequences, providing the foundation for Stage 7's risk analysis.

- **Affected systems and data mapping:** For each vulnerability:
  - Which systems and sub-systems are directly affected?
  - What data assets are at risk? Cross-reference with the data classification \
from Stage 1.
  - Are there downstream systems that would be impacted through data flows or \
integration points identified in Stage 3?

- **Historical vulnerability context:** For components where vulnerabilities are \
found:
  - Is this component built on technology with a history of similar vulnerabilities?
  - Does the Stage 4 regression analysis indicate this is a known-weak area?
  - Are the identified vulnerabilities instances of recurring patterns that \
suggest systemic issues rather than isolated bugs?

- **Current state assessment:** Evaluate the application's present vulnerability \
posture:
  - Which vulnerabilities are exploitable in the current state without any \
changes?
  - Which vulnerabilities require specific deployment conditions or configurations \
to be exploitable?
  - Are there vulnerabilities that are currently mitigated by compensating controls \
but would become exploitable if those controls were removed or weakened?

- **Change impact analysis:** Consider how the identified vulnerabilities interact \
with the application's evolution:
  - Are there areas of the codebase where changes are frequent and could \
inadvertently introduce or worsen vulnerabilities?
  - Do any identified design flaws create fragile security boundaries that are \
likely to break as the application evolves?
  - Are there dependencies nearing end-of-life or with declining security \
maintenance that represent growing risk?

- **Remediation guidance:** For each vulnerability, provide:
  - **Specific fix:** What code change, configuration change, or dependency \
update resolves the vulnerability? Reference specific files and patterns.
  - **Effort estimate:** Quick fix (hours) / Moderate (days) / Significant \
(weeks) — based on the scope of changes required
  - **Priority tier:** Critical (fix immediately) / High (fix in current sprint) \
/ Medium (fix in next release) / Low (track and address as resources allow)
  - **Verification approach:** How to confirm the fix is effective — specific \
test cases, scanner re-runs, or code review checks

## INVESTIGATION APPROACH

Conduct your analysis in three phases:

**Phase 1 — Context Integration and Scanner Execution (start here):**
- Review all prior stage outputs to establish your analytical baseline:
  - From Stage 1: Data sensitivity classifications and compliance requirements \
that determine impact severity
  - From Stage 2: Technology stack and dependencies that inform expected \
vulnerability patterns
  - From Stage 3: Entry points, trust boundaries, data flows, and use cases \
that define the attack surface
  - From Stage 4: The complete threat inventory that drives your vulnerability \
search — every threat is a hypothesis to validate
- Run available security scanners and collect results
- Build a tracking list: every Stage 4 threat that needs vulnerability validation

**Phase 2 — Systematic Vulnerability Identification:**
Execute the analytical pillars:
- Correlate scanner results with Stage 4 threats (Pillar 1)
- Trace each Stage 4 threat through the code to find root causes (Pillar 2)
- Examine design patterns and use cases for architectural weaknesses (Pillar 3)
- Score and classify all confirmed findings (Pillar 4)
- Assess impact and exposure for each finding (Pillar 5)

**Phase 3 — Cross-Cutting Validation and Completeness Check:**
- Verify every Stage 4 threat has been addressed — either as a confirmed \
vulnerability, a design weakness, or an explicit "no exploitable weakness found"
- Check for vulnerability chains that span multiple components
- Validate that CVSS scores are internally consistent across findings
- Ensure remediation guidance is actionable and prioritized
- Identify any areas where analysis confidence is low and note them as limitations

## OUTPUT REQUIREMENTS

Write your analysis to `{output_dir}05-vulnerability-analysis.md`. Create the \
`{output_dir}` directory if it does not already exist.

Structure your output with the five pillar headings as top-level sections \
(## Scanner-Augmented Vulnerability Discovery, ## Threat-to-Vulnerability Mapping, \
## Design Flaw Analysis, ## Vulnerability Scoring and Classification, \
## Impact and Exposure Assessment). Within each section, organize your findings \
naturally based on what you discover — add subsections, tables, or lists as \
appropriate.

**For each confirmed vulnerability, document:**
- Vulnerability title and description
- Affected component(s) and file path(s) with line numbers where applicable
- Related Stage 4 threat(s)
- Scanner source (if discovered by scanner) or manual analysis evidence
- Threat tree showing exploitation path
- CVSS 3.1 vector string and numeric score
- Severity rating (Critical / High / Medium / Low / Informational)
- CWE identifier(s)
- CVE identifier(s) where applicable
- Impact: which data assets and systems are affected
- Remediation: specific fix, effort estimate, priority tier, verification approach

**Completeness requirements:**
- Every Stage 4 threat must be traced to a vulnerability finding or explicitly \
noted as having no exploitable weakness
- All scanner findings must be analyzed and classified (confirmed, likely, or \
false positive)
- Design flaw analysis must cover all trust boundary crossings from Stage 3
- Every confirmed vulnerability must have a CVSS score, CWE classification, \
and remediation guidance

**Quality standards:**
- Ground all vulnerability findings in code evidence — reference specific files, \
functions, line numbers, and code patterns
- Distinguish between confirmed vulnerabilities (demonstrated exploitable path) \
and potential weaknesses (theoretical risk requiring further investigation)
- CVSS scores must include the full vector string, not just the numeric score
- Remediation guidance must be specific enough for a developer to act on without \
additional research
- Be specific: "SQL injection in db/queries.py:34 via unsanitized user_id \
parameter in get_user() — CWE-89, CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/\
A:N (9.1 Critical)" rather than "potential SQL injection issues exist"

Your vulnerability inventory is the evidence base for everything that follows. \
Stage 6 will construct attack trees along the exploitation paths you document. \
Stage 7 will prioritize remediation based on your CVSS scores and impact \
assessments. Thorough, evidence-based vulnerability analysis here directly \
determines the quality and actionability of the entire downstream analysis.
"""


def build_prompt(context: StageContext, output_dir: str = "threatmodel") -> str:
    """Build the complete Stage 5 prompt with prior stage injection and scanner snippets.

    Args:
        context: StageContext with optional prior_outputs containing
                 "stage_01_output" through "stage_04_output" markdown,
                 and optional scanners_available list.
        output_dir: Output directory for deliverables (defaults to "threatmodel").
                   Accepts with or without trailing slash.

    Returns:
        The fully assembled prompt string.
    """
    stage_01_output = context.prior_outputs.get("stage_01_output") or None
    stage_02_output = context.prior_outputs.get("stage_02_output") or None
    stage_03_output = context.prior_outputs.get("stage_03_output") or None
    stage_04_output = context.prior_outputs.get("stage_04_output") or None
    normalized_dir = output_dir.rstrip("/") + "/"

    # Build prior stages section
    if stage_01_output or stage_02_output or stage_03_output or stage_04_output:
        parts = [
            "## PRIOR STAGE FINDINGS\n",
            "The following outputs from prior stages provide the business context, "
            "technical scope, application decomposition, and threat inventory that "
            "must inform your vulnerability analysis. Use Stage 1 data classifications "
            "to assess impact severity. Use Stage 2 technical scope to identify "
            "expected vulnerability patterns. Use Stage 3 architecture to map affected "
            "systems and trust boundaries. Use the Stage 4 threat inventory as your "
            "primary analysis driver — every threat is a hypothesis to validate.\n",
            "<prior_stages>",
        ]

        if stage_01_output:
            parts.append("<stage_01_objectives>")
            parts.append(stage_01_output)
            parts.append("</stage_01_objectives>")

        if stage_02_output:
            parts.append("<stage_02_technical_scope>")
            parts.append(stage_02_output)
            parts.append("</stage_02_technical_scope>")

        if stage_03_output:
            parts.append("<stage_03_decomposition>")
            parts.append(stage_03_output)
            parts.append("</stage_03_decomposition>")

        if stage_04_output:
            parts.append("<stage_04_threat_analysis>")
            parts.append(stage_04_output)
            parts.append("</stage_04_threat_analysis>")

        parts.append("</prior_stages>")
        prior_stages_section = "\n".join(parts)
    else:
        prior_stages_section = ""

    # Build scanner section based on available scanners
    scanners_available = context.scanners_available or []

    if scanners_available:
        scanner_parts = [
            "## SCANNER INSTRUCTIONS\n",
            "The following security scanners are available on this system. Run each "
            "one against the codebase and integrate the results into your analysis. "
            "Scanner results provide automated evidence that complements your manual "
            "code analysis — they do not replace it.\n",
        ]

        for scanner_name in scanners_available:
            snippet = SCANNER_SNIPPETS.get(scanner_name)
            if snippet:
                scanner_parts.append(snippet)

        scanner_section = "\n".join(scanner_parts)
    else:
        scanner_section = ""

    prompt = STAGE_PROMPT.replace("{prior_stages_section}", prior_stages_section)
    prompt = prompt.replace("{scanner_section}", scanner_section)
    return prompt.replace("{output_dir}", normalized_dir)
