"""Framework-aware modeling for web source/sanitizer analysis."""

from __future__ import annotations

from pathlib import Path
from typing import Dict, List


_FRAMEWORK_MARKERS: Dict[str, List[str]] = {
    "nextjs": ["next.config.js", "next.config.ts", "next.config.mjs"],
    "react": ["package.json"],
    "vue": ["vue.config.js", "nuxt.config.js", "nuxt.config.ts"],
    "svelte": ["svelte.config.js", "svelte.config.ts"],
    "angular": ["angular.json"],
}

_FRAMEWORK_SANITIZERS: Dict[str, List[str]] = {
    "nextjs": ["DOMPurify.sanitize", "sanitizeHtml", "escapeHtml(", "validator.escape("],
    "react": ["DOMPurify.sanitize", "sanitizeHtml", "xss(", "escapeHtml("],
    "vue": ["DOMPurify.sanitize", "sanitizeHtml", "xss(", "$sanitize("],
    "svelte": ["DOMPurify.sanitize", "sanitizeHtml", "escapeHtml("],
    "angular": ["DomSanitizer", "sanitize(", "bypassSecurityTrustHtml("],
}

_FRAMEWORK_REDIRECT_ALLOWLIST: Dict[str, List[str]] = {
    "nextjs": ["NextResponse.redirect", "redirect(", "new URL("],
    "react": ["navigate(", "history.push(", "new URL("],
    "vue": ["router.push(", "router.replace(", "new URL("],
    "svelte": ["goto(", "new URL("],
    "angular": ["router.navigate", "router.navigateByUrl", "new URL("],
}


def detect_web_frameworks(project_root: Path, source_blob: str = "") -> List[str]:
    root = Path(project_root)
    detected: List[str] = []
    for fw, markers in _FRAMEWORK_MARKERS.items():
        if any((root / marker).exists() for marker in markers):
            detected.append(fw)
    blob = source_blob.lower()
    if "react" in blob and "react" not in detected:
        detected.append("react")
    return sorted(set(detected))


def get_sanitizers(frameworks: List[str]) -> List[str]:
    out: List[str] = ["DOMPurify.sanitize", "sanitizeHtml", "xss(", "escapeHtml(", "encodeURIComponent("]
    for fw in frameworks:
        out.extend(_FRAMEWORK_SANITIZERS.get(fw, []))
    return sorted(set(out))


def get_redirect_allowlists(frameworks: List[str]) -> List[str]:
    out: List[str] = [
        "allowlist",
        "whitelist",
        "startsWith('/')",
        ".startsWith('/'",
        "new URL(",
        "trustedOrigins",
        "trusted_domains",
    ]
    for fw in frameworks:
        out.extend(_FRAMEWORK_REDIRECT_ALLOWLIST.get(fw, []))
    return sorted(set(out))
