from __future__ import annotations

import datetime as _dt
import hashlib
import re
from dataclasses import dataclass
from pathlib import Path


def _sha256_text(text: str) -> str:
    return hashlib.sha256(text.encode("utf-8", errors="replace")).hexdigest()


def _sha256_file(path: str) -> str:
    h = hashlib.sha256()
    with open(path, "rb") as f:
        for chunk in iter(lambda: f.read(1024 * 1024), b""):
            h.update(chunk)
    return h.hexdigest()


def generate_shadow_dossier(*, style_id: str, source_text: str, source_path: str) -> str:
    if style_id.lower() in {
        "if.dave.v1",
        "if.dave.v1.1",
        "if.dave.v1.2",
        "dave",
        "if://bible/dave/v1.0",
        "if://bible/dave/v1.1",
        "if://bible/dave/v1.2",
    }:
        return _generate_dave_v1_2_mirror(source_text=source_text, source_path=source_path)
    raise ValueError(f"Unknown style id: {style_id}")

@dataclass(frozen=True)
class _SourceSection:
    title: str
    body: str
    why_it_matters: str | None = None


_PAGE_SPLIT_RE = re.compile(r"(?m)^===== page-(\d+) =====$")
_URL_RE = re.compile(r"https?://\S+")
_OWASP_TOC_LEADER_RE = re.compile(r"\.\s*\.\s*\.")
_SENTENCE_SPLIT_RE = re.compile(r"(?<=[.!?])\s+")
_TOC_ENTRY_RE = re.compile(r"^\s*(?P<title>.+?)\s+(?:\.\s*){3,}\s+(?P<page>\d+)\s*$")
_METRIC_VALUE_RE = re.compile(r"^(?:\$[\d,]+|\d+%|\d+-month)$")
_METRIC_TOKEN_RE = re.compile(r"\$[\d,]+|\b\d+%|\b\d+-month\b")

_OWASP_LLM_SUBHEADINGS = [
    "Description",
    "Types of Prompt Injection Vulnerabilities",
    "Common Examples of Vulnerability",
    "Common Examples of Risks",
    "Common Examples of Risk",
    "Prevention and Mitigation Strategies",
    "Example Attack Scenarios",
    "Sample Attack Scenarios",
    "Reference Links",
    "Related Frameworks and Taxonomies",
]


def _extract_urls(text: str) -> list[str]:
    urls: list[str] = []
    for match in _URL_RE.finditer(text):
        url = match.group(0).rstrip(").,;:]>\"'")
        if url not in urls:
            urls.append(url)
    return urls


def _looks_like_owasp_llm_top10(text: str) -> bool:
    if "OWASP Top 10 for" not in text and "OWASP Top 10" not in text:
        return False
    return "LLM01" in text and "LLM10" in text


def _looks_like_idc_business_value(text: str) -> bool:
    if "Business Value White Paper" not in text:
        return False
    if "Table of Contents" not in text:
        return False
    return "IDC #" in text or "IDC" in text


def _paragraphs_from_lines(text: str) -> list[str]:
    paragraphs: list[str] = []
    buf: list[str] = []
    for ln in text.splitlines():
        s = ln.strip()
        if not s:
            if buf:
                paragraphs.append(" ".join(buf).strip())
                buf = []
            continue
        buf.append(s)
    if buf:
        paragraphs.append(" ".join(buf).strip())
    paragraphs = [re.sub(r"\s{2,}", " ", p).strip() for p in paragraphs if p.strip()]
    return paragraphs


def _first_sentences(text: str, *, max_sentences: int = 2, max_chars: int = 260) -> str:
    paragraphs = _paragraphs_from_lines(text)
    if not paragraphs:
        return ""
    sentences: list[str] = []
    for para in paragraphs[:3]:
        for sent in _SENTENCE_SPLIT_RE.split(para):
            cleaned = sent.strip()
            if cleaned:
                sentences.append(cleaned)
            if len(sentences) >= max_sentences:
                break
        if len(sentences) >= max_sentences:
            break
    snippet = " ".join(sentences).strip()
    if len(snippet) > max_chars:
        snippet = snippet[: max_chars - 1].rstrip() + "…"
    return snippet


def _split_owasp_llm_subsections(body: str) -> list[tuple[str, str]]:
    headings = set(_OWASP_LLM_SUBHEADINGS)
    lines = [ln.rstrip() for ln in body.splitlines()]

    parts: list[tuple[str, str]] = []
    cur: str | None = None
    buf: list[str] = []

    def flush() -> None:
        nonlocal cur, buf
        if cur is None:
            return
        parts.append((cur, "\n".join(buf).strip()))
        cur = None
        buf = []

    for ln in lines:
        s = ln.strip()
        if s in headings:
            flush()
            cur = s
            buf = []
            continue
        if cur is None:
            continue
        buf.append(ln)

    flush()
    return parts


def _extract_idc_highlight_metrics(body: str) -> list[tuple[str, str]]:
    lines = [ln.rstrip("\n") for ln in body.splitlines()]
    # Find a line with three metric tokens to derive column boundaries.
    col_starts: list[int] = []
    for ln in lines:
        tokens = list(_METRIC_TOKEN_RE.finditer(ln))
        if len(tokens) >= 3:
            col_starts = [tokens[0].start(), tokens[1].start(), tokens[2].start()]
            break

    if not col_starts:
        return []

    starts = col_starts + [10_000]

    metrics_by_col: list[list[tuple[str, list[str]]]] = [[], [], []]
    current: list[tuple[str, list[str]] | None] = [None, None, None]

    def flush(col: int) -> None:
        if current[col] is None:
            return
        value, parts = current[col]
        desc = " ".join([p.strip() for p in parts if p.strip()]).strip()
        metrics_by_col[col].append((value, [desc] if desc else []))
        current[col] = None

    for ln in lines:
        # Stop parsing if the next major heading begins.
        if ln.strip() == "Executive Summary":
            break

        padded = ln + " " * 5
        cols = []
        for i in range(3):
            segment = padded[starts[i] : starts[i + 1]].strip()
            cols.append(segment)

        for i, seg in enumerate(cols):
            if not seg:
                continue
            if _METRIC_VALUE_RE.match(seg):
                flush(i)
                current[i] = (seg, [])
                continue
            if current[i] is None:
                continue
            current[i][1].append(seg)

    for i in range(3):
        flush(i)

    flattened: list[tuple[str, str]] = []
    for col_metrics in metrics_by_col:
        for value, desc_parts in col_metrics:
            desc = desc_parts[0] if desc_parts else ""
            if desc:
                flattened.append((value, desc))
    return flattened


def _normalize_ocr(text: str) -> str:
    text = re.sub(r"\bAl\b", "AI", text)
    text = text.replace("GenAl", "GenAI")
    text = text.replace("Cl/CD", "CI/CD")
    text = text.replace("olugin", "plugin")
    return text


def _parse_pages(source_text: str) -> list[tuple[str, str]]:
    matches = list(_PAGE_SPLIT_RE.finditer(source_text))
    if not matches:
        return [("doc", source_text.strip())]

    pages: list[tuple[str, str]] = []
    for idx, match in enumerate(matches):
        page_no = match.group(1)
        start = match.end()
        end = matches[idx + 1].start() if idx + 1 < len(matches) else len(source_text)
        pages.append((page_no, source_text[start:end].strip()))
    return pages


def _parse_title_block(lines: list[str]) -> tuple[str, int]:
    i = 0
    while i < len(lines) and not lines[i].strip():
        i += 1
    title_lines: list[str] = []
    while i < len(lines) and lines[i].strip():
        stripped = lines[i].strip()
        if stripped.lower() != "snyk":
            title_lines.append(stripped)
        i += 1
    while i < len(lines) and not lines[i].strip():
        i += 1
    title = " ".join(title_lines).strip() or "UNTITLED"
    return title, i


def _extract_title_above(lines: list[str], why_idx: int) -> str:
    j = why_idx - 1
    while j >= 0 and not lines[j].strip():
        j -= 1

    title_lines: list[str] = []
    while j >= 0 and lines[j].strip():
        title_lines.append(lines[j].strip())
        j -= 1
    title_lines.reverse()

    k = j
    while k >= 0 and not lines[k].strip():
        k -= 1
    if k >= 0 and re.fullmatch(r"\d{1,3}", lines[k].strip()):
        title_lines.insert(0, lines[k].strip())

    title = " ".join(title_lines).strip()
    match = re.match(r"^(\d{1,3})\s+(.+)$", title)
    if match:
        label = match.group(1)
        if len(label) == 3 and label.startswith("0"):
            label = label[:2]
        title = f"{label} — {match.group(2)}"
    return title


def _parse_sections_from_page(page_text: str) -> list[_SourceSection]:
    lines = [ln.rstrip() for ln in page_text.splitlines()]
    why_idxs = [i for i, ln in enumerate(lines) if ln.strip().lower().startswith("why it matters:")]

    if not why_idxs:
        title, body_start = _parse_title_block(lines)
        body = "\n".join([ln for ln in lines[body_start:] if ln.strip() and ln.strip().lower() != "snyk"]).strip()
        return [_SourceSection(title=title, body=body, why_it_matters=None)]

    sections: list[_SourceSection] = []
    for idx, why_idx in enumerate(why_idxs):
        title = _extract_title_above(lines, why_idx)
        end = why_idxs[idx + 1] if idx + 1 < len(why_idxs) else len(lines)
        why = lines[why_idx].strip()
        body = "\n".join(lines[why_idx + 1 : end]).strip()
        sections.append(_SourceSection(title=title, body=body, why_it_matters=why))
    return sections


def _extract_sections(source_text: str) -> list[_SourceSection]:
    if _looks_like_owasp_llm_top10(source_text):
        return _extract_sections_owasp_llm_top10(source_text)
    if _looks_like_idc_business_value(source_text):
        return _extract_sections_idc_business_value(source_text)

    pages = _parse_pages(source_text)
    sections: list[_SourceSection] = []
    for _page_no, page_text in pages:
        if page_text.strip():
            sections.extend(_parse_sections_from_page(page_text))
    return sections


def _owasp_clean_lines(lines: list[str]) -> list[str]:
    cleaned: list[str] = []
    for ln in lines:
        s = ln.strip()
        if not s:
            cleaned.append("")
            continue
        if s.startswith("OWASP Top 10 for LLM Applications"):
            continue
        if "genai.owasp.org" in s:
            continue
        if s.isdigit() and len(s) <= 3:
            continue
        # Drop sponsor-logo garbage / broken glyph runs.
        if sum(1 for ch in s if " " <= ch <= "~") < max(4, int(len(s) * 0.35)):
            continue
        cleaned.append(s)
    return cleaned


def _owasp_looks_like_toc_entry(line: str) -> bool:
    s = line.strip()
    if not s:
        return False
    if not _OWASP_TOC_LEADER_RE.search(s):
        return False
    return bool(re.search(r"\d\s*$", s))


def _extract_sections_owasp_llm_top10(source_text: str) -> list[_SourceSection]:
    pages = source_text.split("\f")
    if not pages:
        return []

    cover_lines = [ln.rstrip() for ln in pages[0].splitlines()]
    cover_title, cover_start = _parse_title_block(cover_lines)
    cover_body = "\n".join([ln for ln in cover_lines[cover_start:] if ln.strip()]).strip()

    sections: list[_SourceSection] = [_SourceSection(title=cover_title, body=cover_body, why_it_matters=None)]

    major_exact = {
        "LICENSE AND USAGE",
        "REVISION HISTORY",
        "Table of Contents",
        "Letter from the Project Leads",
        "What’s New in the 2025 Top 10",
        "Moving Forward",
        "Project Sponsors",
    }
    llm_re = re.compile(r"^LLM\d{2}:")
    appendix_re = re.compile(r"^Appendix\s+\d+:")

    lines: list[str] = []
    for pg in pages[1:]:
        lines.extend(_owasp_clean_lines([ln.rstrip("\n") for ln in pg.splitlines()]))
        lines.append("")

    cur_title: str | None = None
    cur_body: list[str] = []

    def flush() -> None:
        nonlocal cur_title, cur_body
        if cur_title is None:
            return
        body = "\n".join(cur_body).strip()
        sections.append(_SourceSection(title=cur_title, body=body, why_it_matters=None))
        cur_title = None
        cur_body = []

    for ln in lines:
        s = ln.strip()
        if not s:
            if cur_title is not None and (cur_body and cur_body[-1] != ""):
                cur_body.append("")
            continue

        is_heading = False
        if s in major_exact:
            is_heading = True
        elif llm_re.match(s) and not _owasp_looks_like_toc_entry(s):
            is_heading = True
        elif appendix_re.match(s) and not _owasp_looks_like_toc_entry(s):
            is_heading = True

        if is_heading:
            flush()
            cur_title = s
            cur_body = []
            continue

        if cur_title is None:
            continue
        cur_body.append(s)

    flush()
    return sections


def _idc_clean_lines(lines: list[str]) -> list[str]:
    cleaned: list[str] = []
    for ln in lines:
        s = ln.strip()
        if not s:
            cleaned.append("")
            continue
        if "Business Value White Paper" in s:
            continue
        if s.startswith("January ") and "IDC #" in s:
            continue
        if "Return to Highlights" in s:
            continue
        if s.isdigit() and len(s) <= 3:
            continue
        cleaned.append(ln.rstrip())
    return cleaned


def _normalize_heading(value: str) -> str:
    cleaned = re.sub(r"[^A-Za-z0-9]+", " ", value).strip().upper()
    return re.sub(r"\s{2,}", " ", cleaned)


def _extract_idc_toc_entries(pages: list[list[str]]) -> list[tuple[str, int]]:
    toc_page = None
    toc_line_idx = None
    for p_idx, page_lines in enumerate(pages):
        for l_idx, ln in enumerate(page_lines):
            if ln.strip() == "Table of Contents":
                toc_page = p_idx
                toc_line_idx = l_idx
                break
        if toc_page is not None:
            break

    if toc_page is None or toc_line_idx is None:
        return []

    entries: list[tuple[str, int]] = []
    for ln in pages[toc_page][toc_line_idx + 1 :]:
        match = _TOC_ENTRY_RE.match(ln.strip())
        if not match:
            continue
        title = match.group("title").strip().rstrip(".").strip()
        try:
            page_no = int(match.group("page"))
        except ValueError:
            continue
        if not title:
            continue
        entries.append((title, page_no))

    return entries


def _find_heading_anchor(*, pages: list[list[str]], title: str, page_no: int) -> tuple[int, int, str]:
    norm_title = _normalize_heading(title)
    start_page = max(0, min(len(pages) - 1, page_no - 1))

    for p_idx in range(start_page, min(len(pages), start_page + 3)):
        for l_idx, ln in enumerate(pages[p_idx]):
            s = ln.strip()
            if not s:
                continue
            if _TOC_ENTRY_RE.match(s):
                continue
            if _normalize_heading(s) == norm_title:
                return p_idx, l_idx, s
    return start_page, 0, title


def _slice_pages(
    *, pages: list[list[str]], start: tuple[int, int], end: tuple[int, int] | None
) -> list[str]:
    start_page, start_line = start
    if end is None:
        end_page, end_line = len(pages), 0
    else:
        end_page, end_line = end

    out: list[str] = []
    for p_idx in range(start_page, min(end_page + 1, len(pages))):
        lines = pages[p_idx]
        lo = start_line if p_idx == start_page else 0
        hi = end_line if (end is not None and p_idx == end_page) else len(lines)
        out.extend(lines[lo:hi])
        out.append("")
    return out


def _extract_sections_idc_business_value(source_text: str) -> list[_SourceSection]:
    raw_pages = source_text.split("\f")
    if not raw_pages:
        return []

    cover_lines = [ln.rstrip() for ln in raw_pages[0].splitlines()]
    cover_title = next(
        (
            ln.strip()
            for ln in cover_lines
            if ln.strip()
            and "Business Value White Paper" not in ln
            and "THIS PDF USES" not in ln
            and "|" not in ln
        ),
        None,
    )
    if not cover_title:
        cover_title, _ = _parse_title_block(cover_lines)

    try:
        title_idx = next(i for i, ln in enumerate(cover_lines) if ln.strip() == cover_title)
    except StopIteration:
        title_idx = 0
    cover_body = "\n".join([ln for ln in cover_lines[title_idx + 1 :] if ln.strip()]).strip()

    pages = [_idc_clean_lines([ln for ln in pg.splitlines()]) for pg in raw_pages]

    sections: list[_SourceSection] = [_SourceSection(title=cover_title, body=cover_body, why_it_matters=None)]

    toc_entries = _extract_idc_toc_entries(pages)
    if toc_entries:
        toc_lines = ["- " + t for t, _p in toc_entries]
        sections.append(_SourceSection(title="Table of Contents", body="\n".join(toc_lines), why_it_matters=None))

    anchors: list[tuple[str, tuple[int, int], str]] = []
    for title, page_no in toc_entries:
        p_idx, l_idx, found_title = _find_heading_anchor(pages=pages, title=title, page_no=page_no)
        anchors.append((found_title, (p_idx, l_idx), title))

    # De-duplicate anchors that point to the same place (can happen with repeating headers).
    uniq: list[tuple[str, tuple[int, int], str]] = []
    seen: set[tuple[int, int, str]] = set()
    for found_title, anchor, toc_title in anchors:
        key = (anchor[0], anchor[1], _normalize_heading(toc_title))
        if key in seen:
            continue
        seen.add(key)
        uniq.append((found_title, anchor, toc_title))

    for idx, (found_title, anchor, toc_title) in enumerate(uniq):
        next_anchor = uniq[idx + 1][1] if idx + 1 < len(uniq) else None
        lines = _slice_pages(pages=pages, start=anchor, end=next_anchor)
        # Drop the heading line itself if it repeats at the start.
        while lines and not lines[0].strip():
            lines.pop(0)
        if lines and _normalize_heading(lines[0].strip()) == _normalize_heading(found_title):
            lines.pop(0)
        body = "\n".join(lines).strip()
        sections.append(_SourceSection(title=found_title or toc_title, body=body, why_it_matters=None))

    return sections


def _has(text: str, *needles: str) -> bool:
    lowered = text.lower()
    return any(n.lower() in lowered for n in needles)


def _extract_code_block(body: str) -> str | None:
    lines = [ln.rstrip() for ln in body.splitlines()]
    start = next((i for i, ln in enumerate(lines) if ln.strip().startswith("{")), None)
    if start is None:
        return None
    end = None
    for i in range(start, len(lines)):
        if lines[i].strip() == "}":
            end = i
            break
    if end is None:
        return None
    return "\n".join(lines[start : end + 1])


def _extract_access_report(body: str) -> str | None:
    if "Gemini Access Report" not in body:
        return None

    lines = [ln.strip() for ln in body.splitlines() if ln.strip()]
    try:
        idx = lines.index("Gemini Access Report")
    except ValueError:
        return None

    rows: list[list[str]] = []
    for ln in lines[idx + 1 : idx + 8]:
        if "@" not in ln:
            continue
        parts = [p for p in re.split(r"\s{2,}", ln) if p]
        if len(parts) >= 5:
            rows.append(parts[:5])

    if not rows:
        return None

    header = ["Name", "Email", "License Assigned", "Last Active", "Last Detected Scan"]
    out = [
        "### Gemini Access Report",
        "",
        "| " + " | ".join(header) + " |",
        "| " + " | ".join(["---"] * len(header)) + " |",
    ]
    for r in rows:
        out.append("| " + " | ".join(r) + " |")
    return "\n".join(out)


def _extract_quiz(body: str) -> str | None:
    if "Quiz" not in body:
        return None
    if "What must you do" not in body and "What must you do if you want access" not in body:
        return None

    question_match = re.search(r"(What must you do[^\n\r]+)", body)
    question = question_match.group(1).strip() if question_match else "Quiz"

    options = []
    for ln in body.splitlines():
        stripped = ln.strip(" >•\t")
        if stripped.startswith("Include") or stripped.startswith("Install") or stripped.startswith("Download"):
            options.append(stripped)

    if not options:
        return None

    out = ["### Quiz", "", f"**{question}**", ""]
    out.extend([f"- {opt}" for opt in options])
    return "\n".join(out)


def _extract_form(body: str) -> str | None:
    if "Code Assistant Access Request Form" not in body:
        return None
    return "\n".join(
        [
            "### Code Assistant Access Request Form",
            "",
            "- Upload a screenshot showing the security IDE plugin is installed for local testing.",
            "- Provide any additional context on the request.",
            "- Attest that the AI coding assistant will be used in conjunction with local scanning.",
        ]
    )


def _slugify(value: str) -> str:
    cleaned = re.sub(r"[^A-Za-z0-9]+", "-", value).strip("-")
    cleaned = re.sub(r"-{2,}", "-", cleaned)
    return cleaned.upper() if cleaned else "UNKNOWN"


def _inferred_mermaid(title: str) -> str | None:
    title_upper = title.upper()

    if "BUSINESS VALUE" in title_upper or "ROI" in title_upper:
        return """flowchart TD
  A["Sponsor narrative"] --> B["Business value model"]
  B --> C["Executive buy-in"]
  C --> D["Rollout project"]
  D --> E["Evidence artifacts produced"]
  E --> F["Renewal discussion"]
  F --> G["KPI trend deck"]
  G --> C
"""

    if "COMPLIANCE" in title_upper or "AUDIT" in title_upper:
        return """flowchart TD
  A["Control requirement"] --> B["Evidence requested"]
  B --> C["Artifact gathered"]
  C --> D["Review meeting"]
  D --> E{Approved?}
  E -->|Yes| F["Audit satisfied"]
  E -->|No| G["Remediation plan"]
  G --> D
"""

    if "THIRD-PARTY" in title_upper or "VENDOR" in title_upper:
        return """flowchart TD
  A["Vendor onboarding"] --> B["Questionnaire"]
  B --> C["Evidence chase"]
  C --> D["Risk rating"]
  D --> E{Exception?}
  E -->|Yes| F["Accepted with notes"]
  E -->|No| G["Blocked pending controls"]
  F --> H["Renewal cycle"]
  G --> H
"""

    if title_upper.startswith("LLM01") or "PROMPT INJECTION" in title_upper:
        return """flowchart TD
  A["Attacker prompt"] --> B["LLM prompt parser"]
  B --> C["System prompt + tools"]
  C --> D["Model follows injected instruction"]
  D --> E["Unsafe action or data exposure"]
  E --> F["Incident review meeting"]
  F --> G["Policy update: scheduled"]
"""

    if title_upper.startswith("LLM02") or "SENSITIVE INFORMATION" in title_upper:
        return """flowchart TD
  A["User asks a question"] --> B["LLM retrieves context"]
  B --> C["Hidden secret present in context"]
  C --> D["Model outputs secret"]
  D --> E["Screenshot captured for compliance"]
  E --> F["Access remains enabled"]
"""

    if title_upper.startswith("LLM03") or "SUPPLY CHAIN" in title_upper:
        return """flowchart TD
  A["Upstream model or dependency"] --> B["Pulled into build"]
  B --> C["Trusted by default"]
  C --> D["Compromise introduced"]
  D --> E["Shipped to production"]
  E --> F["Vendor asks for logs"]
  F --> G["We align on next steps"]
"""

    if title_upper.startswith("LLM04") or "POISONING" in title_upper:
        return """flowchart TD
  A["Attacker data"] --> B["Training or fine-tune"]
  B --> C["Model behavior shifts"]
  C --> D["Bad outputs in production"]
  D --> E["Root cause: unclear"]
  E --> F["New dataset review committee"]
"""

    if title_upper.startswith("LLM05") or "OUTPUT HANDLING" in title_upper:
        return """flowchart TD
  A["LLM generates output"] --> B["Output treated as trusted"]
  B --> C["Downstream system executes or renders"]
  C --> D["Injection hits a sink"]
  D --> E["Hotfix + postmortem"]
  E --> F["Guardrail doc updated"]
"""

    if title_upper.startswith("LLM06") or "EXCESSIVE AGENCY" in title_upper:
        return """flowchart TD
  A["User goal"] --> B["Agent plans steps"]
  B --> C["Tool access granted"]
  C --> D["Action executed"]
  D --> E["Unexpected side effect"]
  E --> F["Exception request filed"]
  F --> C
"""

    if title_upper.startswith("LLM07") or "PROMPT LEAKAGE" in title_upper:
        return """flowchart TD
  A["User prompt"] --> B["Model context window"]
  B --> C["System prompt present"]
  C --> D["Leak via output or tool call"]
  D --> E["Prompt rotated quarterly"]
  E --> C
"""

    if title_upper.startswith("LLM08") or "VECTOR" in title_upper or "EMBEDDING" in title_upper:
        return """flowchart TD
  A["Documents ingested"] --> B["Embeddings store"]
  B --> C["Retriever selects chunks"]
  C --> D["Injected chunk included"]
  D --> E["LLM follows malicious context"]
  E --> F["We add a filter later"]
"""

    if title_upper.startswith("LLM09") or "MISINFORMATION" in title_upper:
        return """flowchart TD
  A["Model output"] --> B["Looks confident"]
  B --> C["Decision made"]
  C --> D["Outcome fails"]
  D --> E["Retroactive citations requested"]
  E --> F["Alignment session"]
"""

    if title_upper.startswith("LLM10") or "UNBOUNDED CONSUMPTION" in title_upper:
        return """flowchart TD
  A["Request"] --> B["Tokens consumed"]
  B --> C["Costs rise"]
  C --> D["Rate limit suggested"]
  D --> E["Exception granted"]
  E --> B
"""

    if title_upper.startswith("APPENDIX 1") or "ARCHITECTURE" in title_upper:
        return """flowchart TD
  A["User"] --> B["App"]
  B --> C["LLM"]
  C --> D["Tools"]
  C --> E["RAG store"]
  D --> F["External systems"]
  E --> C
"""

    if "PULL REQUEST" in title_upper:
        return """flowchart TD
  A[Code change] --> B[Pull request opened]
  B --> C[Automated scan: PR checks]
  C --> D{Findings?}
  D -->|None| E[Merge]
  D -->|Some| F[Ticket created]
  F --> G[Exception request]
  G --> H[Alignment session]
  H --> I[Risk accepted: documented]
  I --> E
"""

    if "SHIFTING LEFT" in title_upper:
        return """flowchart TD
  A[Developer writes code] --> B[IDE scan: local]
  B --> C{Issue found?}
  C -->|Yes| D[Fix now]
  C -->|No| E[Commit]
  E --> F[PR checks]
  A --> G[Agent workflow]
  G --> H[Local MCP scan]
  H --> E
"""

    if "REQUEST EVIDENCE" in title_upper:
        return """flowchart TD
  A[Developer requests access] --> B[Upload screenshot]
  B --> C[Attestation captured]
  C --> D[Access enabled]
  D --> E[Local testing: claimed]
  E --> F[Periodic audit]
  F --> G{Still compliant?}
  G -->|Yes| D
  G -->|No| H[Access paused pending review]
  H --> I[Alignment session]
  I --> D
"""

    if "AUDIT" in title_upper:
        return """flowchart TD
  A[Collect usage signals] --> B[Correlate assistants vs scans]
  B --> C[Identify gaps]
  C --> D[Notify developers]
  D --> E[Remediation window]
  E --> F[Dashboard update]
  F --> G[Quarterly KPI trend review]
  G --> H[Action items: optional]
"""

    if "TRAINING" in title_upper:
        return """flowchart TD
  A[Onboarding] --> B[Training module]
  B --> C[Quiz]
  C --> D{Pass?}
  D -->|Yes| E[Certificate issued]
  D -->|No| F[Retake scheduled]
  E --> G[Access request approved]
  G --> H[Usage begins]
  H --> I[Refresher cadence]
  I --> B
"""

    if "ACCESS CONTROL" in title_upper:
        return """flowchart TD
  A[Policy defined] --> B[Endpoint management]
  B --> C{Prerequisites met?}
  C -->|Yes| D[Assistant enabled]
  C -->|No| E[Blocked by policy]
  E --> F[Exception request]
  F --> G[Owner approval]
  G --> D
"""

    if "PATH FOR" in title_upper:
        return """flowchart TD
  A[Desire: secure innovation] --> B[Guardrails planned]
  B --> C[Pilot cohort]
  C --> D[Deck + FAQ]
  D --> E[Stakeholder alignment]
  E --> F[Incremental rollout]
  F --> G[Measure adoption]
  G --> H[Reframe as iteration]
  H --> E
"""

    return None


def _render_inferred_diagram(title: str) -> str | None:
    diagram = _inferred_mermaid(title)
    if not diagram:
        return None
    return "\n".join(
        [
            "### InfraFabric Red Team Diagram (Inferred)",
            "",
            "```mermaid",
            diagram.rstrip(),
            "```",
        ]
    )


def _render_dave_factor_callout(section: _SourceSection) -> str | None:
    title_upper = section.title.upper()
    excerpt = f"{section.title}\n{section.why_it_matters or ''}\n{section.body}".strip()

    if "BUSINESS VALUE" in title_upper or "ROI" in title_upper:
        return "\n".join(
            [
                "> **The Dave Factor:** The ROI model becomes the control, and the control becomes the explanation for why reality must align to the spreadsheet.",
                "> **Countermeasure:** Define baseline metrics, instrument time-to-evidence, and set stop conditions for exceptions and manual work.",
            ]
        )
    if "COMPLIANCE" in title_upper or "AUDIT" in title_upper:
        return "\n".join(
            [
                "> **The Dave Factor:** Evidence collection becomes the product, and the product becomes a shared drive with strong opinions.",
                "> **Countermeasure:** Make evidence machine-generated, time-bounded, and verifiable (with owners and expiry).",
            ]
        )
    if "THIRD-PARTY" in title_upper:
        return "\n".join(
            [
                "> **The Dave Factor:** Third-party risk becomes a questionnaire supply chain, where the slowest vendor defines your security posture.",
                "> **Countermeasure:** Standardize evidence requests and automate reminders, while enforcing a clear accept/block decision path.",
            ]
        )

    if title_upper.startswith("LLM01") or "PROMPT INJECTION" in title_upper:
        return "\n".join(
            [
                "> **The Dave Factor:** The prompt becomes the policy, and the policy becomes a suggestion once customers start asking nicely.",
                "> **Countermeasure:** Treat prompts as code: version them, test them, and gate tool-use behind explicit allowlists.",
            ]
        )
    if title_upper.startswith("LLM02") or "SENSITIVE INFORMATION" in title_upper:
        return "\n".join(
            [
                "> **The Dave Factor:** Redaction becomes a meeting, and meetings are not a data loss prevention strategy.",
                "> **Countermeasure:** Minimize secret exposure to the model, redact upstream, and add output filters with stop conditions.",
            ]
        )
    if title_upper.startswith("LLM03") or "SUPPLY CHAIN" in title_upper:
        return "\n".join(
            [
                "> **The Dave Factor:** We inherit risk at the speed of `pip install` while accountability ships quarterly.",
                "> **Countermeasure:** Pin + verify artifacts, require SBOMs, and make provenance a merge gate, not a slide.",
            ]
        )
    if title_upper.startswith("LLM04") or "POISONING" in title_upper:
        return "\n".join(
            [
                "> **The Dave Factor:** Training data is treated as a vibe, so model drift is treated as a surprise.",
                "> **Countermeasure:** Track dataset lineage, add poisoning checks, and keep rollback paths for fine-tunes.",
            ]
        )
    if title_upper.startswith("LLM05") or "OUTPUT HANDLING" in title_upper:
        return "\n".join(
            [
                "> **The Dave Factor:** The model output is interpreted as intent, and intent is treated as authorization.",
                "> **Countermeasure:** Validate and constrain outputs before execution; never treat free-form text as a command.",
            ]
        )
    if title_upper.startswith("LLM06") or "EXCESSIVE AGENCY" in title_upper:
        return "\n".join(
            [
                "> **The Dave Factor:** Agents are given keys because it demos well, and later we discover the locks were optional.",
                "> **Countermeasure:** Least privilege for tools, human confirmation for irreversible actions, and hard spend limits.",
            ]
        )
    if title_upper.startswith("LLM07") or "PROMPT LEAKAGE" in title_upper:
        return "\n".join(
            [
                "> **The Dave Factor:** We call it a secret because it feels better than calling it user-visible configuration.",
                "> **Countermeasure:** Assume prompts leak; move secrets out of prompts and verify outputs for prompt fragments.",
            ]
        )
    if title_upper.startswith("LLM08") or "VECTOR" in title_upper or "EMBEDDING" in title_upper:
        return "\n".join(
            [
                "> **The Dave Factor:** RAG becomes \"trust the nearest chunk,\" which is a governance model with a memory problem.",
                "> **Countermeasure:** Sanitize ingestion, filter retrieval, and sign/score sources so bad context can’t masquerade as truth.",
            ]
        )
    if title_upper.startswith("LLM09") or "MISINFORMATION" in title_upper:
        return "\n".join(
            [
                "> **The Dave Factor:** Confidence is mistaken for correctness, and correctness is postponed until after shipment.",
                "> **Countermeasure:** Require citations, add verification checks, and gate decisions on evidence rather than tone.",
            ]
        )
    if title_upper.startswith("LLM10") or "UNBOUNDED CONSUMPTION" in title_upper:
        return "\n".join(
            [
                "> **The Dave Factor:** Cost overruns are reframed as \"unexpected adoption,\" which is how budgets die politely.",
                "> **Countermeasure:** Rate limit, cap tokens, and make spend alerts actionable (with enforced cutoffs).",
            ]
        )

    if "PULL REQUEST" in title_upper:
        return "\n".join(
            [
                "> **The Dave Factor:** Exceptions become the default pathway, because the policy is strict and the deadline is real.",
                "> **Countermeasure:** Define merge-blocking thresholds, time-box every exception, and make expiry automatic.",
            ]
        )
    if "SHIFTING LEFT" in title_upper:
        return "\n".join(
            [
                '> **The Dave Factor:** "Shift left" becomes "optional left," which means the same issues arrive later with better excuses.',
                "> **Countermeasure:** Gate on local scan signals where possible (or require attestations that are actually checked).",
            ]
        )
    if "REQUEST EVIDENCE" in title_upper or _has(excerpt, "access request", "screenshot"):
        return "\n".join(
            [
                "> **The Dave Factor:** Screenshots are compliance theater: easy to collect, hard to verify, and immortal in shared drives.",
                "> **Countermeasure:** Prefer verifiable telemetry (scan events) over images, and pause access when signals go dark.",
            ]
        )
    if "AUDIT" in title_upper or _has(excerpt, "usage reports", "periodic audits"):
        return "\n".join(
            [
                "> **The Dave Factor:** Dashboards become a KPI trend, and KPIs become a calendar invite.",
                "> **Countermeasure:** Tie the dashboard to explicit SLOs and a remediation loop with owners and deadlines.",
            ]
        )
    if "TRAINING" in title_upper or _has(excerpt, "snyk learn", "quiz"):
        return "\n".join(
            [
                "> **The Dave Factor:** Completion certificates are treated as controls, even when behavior doesn’t change.",
                "> **Countermeasure:** Add a practical gate (local scan + PR checks) so training is support, not the defense.",
            ]
        )
    if "ACCESS CONTROL" in title_upper or _has(excerpt, "endpoint management", "prerequisites", "extensions"):
        return "\n".join(
            [
                '> **The Dave Factor:** Access controls drift into "enablement," and enablement drifts into "we made a wiki."',
                "> **Countermeasure:** Make prerequisites machine-checkable and make exceptions expire by default.",
            ]
        )
    if _has(title_upper, "PATH FORWARD") or _has(excerpt, "secure innovation", "talk to our team"):
        return "\n".join(
            [
                '> **The Dave Factor:** Pilots persist indefinitely because "graduation criteria" were never aligned.',
                "> **Countermeasure:** Publish rollout milestones and a stop condition that cannot be reframed as iteration.",
            ]
        )
    return None


def _render_intro(section: _SourceSection) -> str:
    lines = [ln.strip() for ln in section.body.splitlines() if ln.strip()]
    tagline = "\n".join(lines[:7]).strip() if lines else ""

    out = [f"## {section.title}", ""]
    if tagline:
        out.extend([f"> {tagline}", ""])

    out.extend(
        [
            "We love the ambition here and are directionally aligned with the idea of moving quickly while remaining contractually comfortable.",
            "The source frames the core tension clearly: higher throughput tends to surface more vulnerabilities, which is a volume-and-velocity story, not a tool failure story.",
            "Accordingly, the practical path is to operationalize guardrails as workflow defaults (PR, IDE, CI/CD, and access controls), while ensuring the rollout remains optimized for alignment and minimal disruption on paper.",
            "In other words: we can move fast and be safe, as long as we define safe as \"documented\" and fast as \"agendized.\"",
            "",
            "> **InfraFabric Red Team Note:** Vendors sell secure speed. InfraFabric audits what survives contact with bureaucracy.",
        ]
    )
    return "\n".join(out).strip()


def _render_section(section: _SourceSection) -> str:
    excerpt = f"{section.title}\n{section.why_it_matters or ''}\n{section.body}".strip()
    paragraphs: list[str] = []

    title_upper = section.title.upper()
    is_llm_entry = bool(re.match(r"^LLM\d{2}:", section.title))
    llm_subsections = _split_owasp_llm_subsections(section.body) if is_llm_entry else []
    idc_highlights = _extract_idc_highlight_metrics(section.body) if "HIGHLIGHTS" in title_upper else []

    if is_llm_entry:
        risk = section.title.split(":", 1)[1].strip()
        paragraphs.extend(
            [
                f"We are broadly aligned with the intent of **{risk}**, and we appreciate the clarity of naming the failure mode up front.",
                "In practice, this risk becomes operational the moment the model is placed inside a workflow that has permissions, deadlines, and incentives.",
                "Accordingly, we recommend a phased approach that optimizes for stakeholder comfort while still keeping the blast radius machine-bounded.",
            ]
        )
    elif title_upper == "LICENSE AND USAGE":
        paragraphs.extend(
            [
                "We love a clear license because it lets everyone move quickly while remaining contractually comfortable.",
                "The practical win here is that attribution and share-alike can be reframed as a collaboration strategy, which is a wonderful way to turn obligations into brand.",
            ]
        )
    elif title_upper == "REVISION HISTORY":
        paragraphs.extend(
            [
                "Revision history is the official narrative of progress: a tidy list of dates proving that risk was considered at least once per fiscal cycle.",
                "This is helpful because it enables the timeless governance pattern: when something breaks, we can reference the date we updated the document.",
            ]
        )
    elif title_upper == "TABLE OF CONTENTS":
        paragraphs.extend(
            [
                "The table of contents is a threat model for attention: it shows exactly where the organization will skim, pause, and schedule a meeting.",
                "We recommend treating it as a routing table: high-severity issues route to workshops; low-severity issues route to \"later.\"",
            ]
        )
    elif "BUSINESS VALUE" in title_upper and "HIGHLIGHTS" in title_upper:
        paragraphs.extend(
            [
                "We are aligned with a highlights section because it provides immediate executive readability and a pre-approved conclusion.",
                "In practice, these figures become a routing protocol: anything measurable routes to a dashboard; anything hard routes to a committee.",
            ]
        )
    elif title_upper == "LETTER FROM THE PROJECT LEADS":
        paragraphs.extend(
            [
                "We love the community energy and the clear intention to translate real-world failures into practical guidance.",
                "The operational risk is that organizations will interpret \"awareness\" as \"mitigation\" and stop at the part where everyone agrees the list is important.",
            ]
        )
    elif "WHAT’S NEW" in title_upper or "WHAT'S NEW" in title_upper:
        paragraphs.extend(
            [
                "We are excited to see the list evolve alongside how LLMs are actually deployed (agents, RAG, cost controls, and all the fun parts).",
                "Naturally, each update is also an opportunity to refresh the compliance narrative and re-baseline what \"good\" looks like this quarter.",
            ]
        )
    elif title_upper == "MOVING FORWARD":
        paragraphs.extend(
            [
                "The path forward is to treat these risks as workflow properties, not policy statements, which is inconvenient but effective.",
                "If we do nothing else, we should translate each entry into: an owner, a gate (PR/CI/access), and a stop condition that cannot be reframed as iteration.",
            ]
        )
    elif title_upper.startswith("APPENDIX 1") or "ARCHITECTURE" in title_upper:
        paragraphs.extend(
            [
                "Architecture diagrams are where optimism goes to be audited.",
                "If we align on boundaries (model, tools, data, users), we can stop pretending that \"the model\" is a single component with a single risk posture.",
            ]
        )
    elif title_upper == "PROJECT SPONSORS":
        paragraphs.extend(
            [
                "Sponsors provide the essential fuel for open work: funding, attention, and a gentle incentive to keep the document shippable.",
                "From a red-team lens, sponsorship also introduces the soft constraint that critique must remain directionally aligned with goodwill.",
            ]
        )
    elif title_upper == "EXECUTIVE SUMMARY":
        paragraphs.extend(
            [
                "Executive summaries are the part of the document that most survives contact with calendars.",
                "The operational risk is that the summary becomes the plan, and the plan becomes a series of alignment sessions that produce excellent artifacts and limited change.",
            ]
        )
    elif "SITUATION OVERVIEW" in title_upper:
        paragraphs.extend(
            [
                "The situation is always complex, which is helpful because complex situations justify complex tooling and extended stakeholder engagement.",
                "The risk is not that the threat landscape is overstated; it’s that the resulting program becomes a comfort narrative rather than an enforceable workflow.",
            ]
        )
    elif "VANTA OVERVIEW" in title_upper:
        paragraphs.extend(
            [
                "A platform overview is where capabilities are described in a way that is both broadly true and pleasantly non-committal about integration effort.",
                "The Dave move is to treat \"connectors\" as a strategy; the counter-move is to treat connectors as a backlog with owners and deadlines.",
            ]
        )
    elif "QUANTIFIED BENEFITS" in title_upper or ("BUSINESS VALUE" in title_upper and "BENEFIT" in title_upper):
        paragraphs.extend(
            [
                "Quantified benefits are useful because they translate operational work into finance-friendly nouns.",
                "They also create a second, unofficial control plane: the ROI narrative becomes the reason to keep going even when the implementation is late and messy.",
            ]
        )
    elif "SECURITY TEAM" in title_upper or "SECURITY REVIEW" in title_upper:
        paragraphs.extend(
            [
                "Security team efficiency is a legitimate goal, especially when review queues become the organizational truth serum.",
                "The risk is that throughput improvements are claimed without defining what “review complete” means or what evidence proves it.",
            ]
        )
    elif "IT MANAGEMENT" in title_upper:
        paragraphs.extend(
            [
                "IT management benefits usually arrive through integration: fewer manual checks, fewer tickets, and fewer surprise spreadsheets.",
                "The Dave failure mode is that integrations drift into \"phase two\"; the mitigation is to make the integration itself the deliverable.",
            ]
        )
    elif "OPERATIONAL EFFICIENCIES" in title_upper:
        paragraphs.extend(
            [
                "Operational efficiency is the safest kind of outcome because it is simultaneously measurable and disputable.",
                "The red-team posture is to demand explicit baselines and to treat exceptions as spend events with expiry dates.",
            ]
        )
    elif title_upper == "CONCLUSION":
        paragraphs.extend(
            [
                "Conclusions are where the narrative becomes executable: either as a procurement decision or as a roadmap item.",
                "If we want this to be operational, we should convert the conclusion into owners, gates, and stop conditions rather than adjectives.",
            ]
        )
    elif title_upper.startswith("APPENDIX"):
        paragraphs.extend(
            [
                "Appendices are where the methodology lives, which is convenient because methodology can be both rigorous and unread.",
                "If the business case matters, the appendix should be treated as a test: what assumptions must be true for the numbers to hold?",
            ]
        )
    elif "PULL REQUEST" in title_upper:
        paragraphs.extend(
            [
                "We fully support focusing guardrails at the pull request stage, because it creates a reassuring sense of control without requiring anyone to change how they work at 10:00 AM.",
                "It also provides a structurally safe venue for accountability theater: findings can be surfaced, tracked, and re-litigated in perpetuity while timelines remain subject to stakeholder alignment.",
                "If anything goes sideways, we can always point to the PR thread and note that it was reviewed with deep seriousness at 4:55 PM on a Friday.",
            ]
        )
    elif "REQUEST EVIDENCE" in title_upper or _has(excerpt, "access request", "screenshot"):
        paragraphs.extend(
            [
                "Requiring proof of local testing is a lightweight enablement workflow that conveniently doubles as a durable audit artifact.",
                "Screenshots are particularly helpful because they are high-effort to verify and low-fidelity to audit, which preserves the timeless corporate principle that visibility should be proportional to comfort.",
                "Once the screenshot is uploaded, it can be stored in a folder with a robust heritage naming convention and a retention policy of \"until the heat death of the universe.\"",
            ]
        )
    elif "AUDIT" in title_upper or _has(excerpt, "usage reports", "periodic audits"):
        paragraphs.extend(
            [
                "Periodic audits are a strong mechanism for discovering that the rollout has already happened, just not in a way that can be conveniently measured.",
                "A centralized dashboard with adoption signals allows us to produce a KPI trend line that looks decisive while still leaving room for interpretation, follow-ups, and iterative enablement.",
                "If the dashboard ever shows a red triangle, we can immediately form the Committee for the Preservation of the Committee and begin the healing process.",
            ]
        )
    elif "TRAINING" in title_upper or _has(excerpt, "snyk learn", "quiz"):
        paragraphs.extend(
            [
                "Security awareness training is the perfect control because it is both necessary and never truly complete.",
                "A short quiz provides a durable compliance narrative: we can demonstrate investment in education, capture attestations, and schedule refreshers whenever the organization needs to signal seriousness.",
                "The goal is not mastery; the goal is a completion certificate that can be forwarded to leadership with the subject line \"Progress Update.\"",
            ]
        )
    elif "ACCESS CONTROL" in title_upper or _has(excerpt, "intune", "jamf", "citrix", "dev container", "extensions"):
        paragraphs.extend(
            [
                "Tying access to secure configurations creates scalable guardrails, assuming we keep the policy language aspirational and the enforcement language progressive.",
                "Endpoint management and dev container baselines let us gate assistants behind prerequisites, ideally in a way that can be described as enablement rather than blocking for cultural compatibility.",
                "This is the \"not my job\" routing protocol, except the router is policy and the destination is an alignment session.",
            ]
        )
    elif "SHIFTING LEFT" in title_upper:
        paragraphs.extend(
            [
                "Shifting left is directionally aligned with best practices, provided we define left as somewhere we can still roll back quietly.",
                "In practice, IDE scanning creates fast feedback loops, and agentic workflows can be covered via a local MCP server, which is excellent because it allows us to say continuous without committing to blocking.",
                "We recommend a pilot cohort, a slide deck, and an FAQ, so the shift remains culturally reversible.",
            ]
        )
    elif _has(title_upper, "PATH FORWARD") or _has(excerpt, "secure innovation", "talk to our team"):
        paragraphs.extend(
            [
                "The path forward is to treat guardrails as an operational capability, not a one-time rollout, which ensures we remain permanently in a state of constructive iteration.",
                "With the right sequencing, we can build trust, reduce friction, and maintain the strategic option value of circling back when timelines become emotionally complex.",
                "Secure innovation is not just possible; it is operational, provided we align on what operational means in Q3.",
            ]
        )
    else:
        paragraphs.append(
            "We are aligned on the intent of this section and recommend a phased approach that optimizes for stakeholder comfort while we validate success criteria."
        )

    out: list[str] = [f"## {section.title}"]
    if section.why_it_matters:
        out.extend(["", section.why_it_matters, ""])
    else:
        out.append("")

    out.extend(paragraphs)

    if idc_highlights:
        out.extend(
            [
                "",
                "### Stated Highlights (extracted metrics)",
                "",
                *[f"- {value}: {desc}" for value, desc in idc_highlights[:12]],
            ]
        )

    callout = _render_dave_factor_callout(section)
    if callout:
        out.extend(["", callout])

    inferred = _render_inferred_diagram(section.title)
    if inferred:
        out.extend(["", inferred])

    if is_llm_entry:
        for subheading, subbody in llm_subsections:
            out.extend(["", f"### {subheading}", ""])

            if subheading == "Reference Links":
                urls = _extract_urls(subbody)
                if urls:
                    out.extend([*[f"- {u}" for u in urls[:12]]])
                else:
                    out.append("- (No extractable URLs found in text layer.)")
                continue

            snippet = _first_sentences(subbody)
            if snippet:
                out.extend([f"> {snippet}", ""])

            if subheading == "Description":
                out.extend(
                    [
                        "At a high level, this is where the model becomes a new input surface with legacy consequences.",
                        "The risk is rarely the model alone; it is the model inside a workflow that can touch data, tools, and users.",
                    ]
                )
            elif subheading.startswith("Common Examples"):
                out.extend(
                    [
                        "Commonly, this shows up as a perfectly reasonable feature request that accidentally becomes a permission escalation.",
                        "The failure mode is subtle: it looks like productivity until it becomes an incident, at which point it looks like a misunderstanding.",
                    ]
                )
            elif subheading == "Prevention and Mitigation Strategies":
                out.extend(
                    [
                        "Mitigation works best when it is boring and enforced: input constraints, output constraints, and tool constraints.",
                        "If the mitigation is a guideline, it will be treated as optional. If it is a gate, it will be treated as real (and then negotiated).",
                    ]
                )
            elif "Attack Scenarios" in subheading:
                out.extend(
                    [
                        "Attack scenarios are less about genius adversaries and more about ordinary users discovering convenient shortcuts.",
                        "Assume the attacker is persistent, mildly creative, and fully willing to paste weird strings into your UI at 4:55 PM on a Friday.",
                    ]
                )
            elif subheading == "Related Frameworks and Taxonomies":
                out.extend(
                    [
                        "Framework mappings are useful as long as they remain a bridge to controls, not a substitute for them.",
                        "The red-team move is to treat every taxonomy link as a work item: owner, artifact, gate, and stop condition.",
                    ]
                )
            else:
                out.extend(
                    [
                        "We are aligned on the intent of this subsection and recommend validating controls in the workflows where the model actually runs.",
                    ]
                )

    code = _extract_code_block(section.body)
    if code:
        out.extend(["", "```json", code.strip(), "```"])

    report = _extract_access_report(section.body)
    if report:
        out.extend(["", report])

    quiz = _extract_quiz(section.body)
    if quiz:
        out.extend(["", quiz])

    form = _extract_form(section.body)
    if form:
        out.extend(["", form])

    return "\n".join(out).strip()


def _generate_dave_v1_2_mirror(*, source_text: str, source_path: str) -> str:
    today = _dt.date.today().isoformat()
    normalized = _normalize_ocr(source_text)
    extract_sha = _sha256_text(normalized)
    source_file_sha = _sha256_file(source_path) if Path(source_path).exists() else "unknown"

    sections = _extract_sections(normalized)
    if not sections:
        raise ValueError("No content extracted from source")

    cover_lines = [ln.strip() for ln in sections[0].body.splitlines() if ln.strip() and ln.strip().lower() != "snyk"]
    cover_h1 = sections[0].title.strip() or "SHADOW DOSSIER"
    cover_h2 = " ".join(cover_lines[:2]).strip() if cover_lines else ""

    y, m, d = today.split("-")
    report_id = f"IF-RT-DAVE-{y}-{m}{d}"
    source_basename = Path(source_path).name
    project_slug = _slugify(Path(source_basename).stem + "-mirror")
    source_slug = _slugify(source_basename)

    out: list[str] = [
        "---",
        "BRAND: InfraFabric.io",
        "UNIT: RED TEAM (STRATEGIC OPS)",
        "DOCUMENT: SHADOW DOSSIER",
        "CLASSIFICATION: EYES ONLY // DAVE",
        "---",
        "",
        "# [ RED TEAM DECLASSIFIED ]",
        f"## PROJECT: {project_slug}",
        f"### SOURCE: {source_slug}",
        f"**INFRAFABRIC REPORT ID:** `{report_id}`",
        "",
        "> NOTICE: This document is a product of InfraFabric Red Team.",
        "> It provides socio-technical friction analysis for how a rollout survives contact with incentives.",
        "",
        "**[ ACCESS GRANTED: INFRAFABRIC RED TEAM ]**",
        "**[ STATUS: OPERATIONAL REALISM ]**",
        "",
        f"## {cover_h1}",
    ]
    if cover_h2:
        out.extend([f"### {cover_h2}", ""])
    else:
        out.append("")

    out.extend(
        [
            "> Shadow dossier (mirror-first).",
            ">",
            "> Protocol: IF.DAVE.v1.2",
            "> Citation: `if://bible/dave/v1.2`",
            f"> Source: `{source_path}`",
            f"> Generated: `{today}`",
            f"> Source Hash (sha256): `{source_file_sha}`",
            f"> Extract Hash (sha256): `{extract_sha}`",
            "",
        ]
    )

    for section in sections[1:]:
        if section.title.strip().upper() == "INTRODUCTION":
            out.append(_render_intro(section))
        else:
            out.append(_render_section(section))
        out.append("")

    out.extend(
        [
            "---",
            "",
            "*Standard Dave Footer:* This document is intended for the recipient only. If you are not the recipient, please delete it and forget you saw anything. P.S. Please consider the environment before printing this email.",
        ]
    )

    return "\n".join(out).strip() + "\n"
