"""Layer 1 — Static analysis: typosquatting, metadata, AST, obfuscation, CVE, maintainer."""
from __future__ import annotations

from pyguard.detectors.ast_analyzer import analyze_source
from pyguard.detectors.cve import find_cves
from pyguard.detectors.maintainer import analyze_maintainer
from pyguard.detectors.obfuscation import analyze_obfuscation
from pyguard.detectors.typosquatting import build_findings as build_typosquat_findings
from pyguard.layers.base import BaseLayer
from pyguard.models import Finding, PackageInfo

# Files most likely to contain install-time hooks — analysed first
_HIGH_PRIORITY = {"setup.py", "setup.cfg", "pyproject.toml"}


class StaticAnalysisLayer(BaseLayer):
    name = "static"

    async def analyze(self, package: PackageInfo) -> list[Finding]:
        findings: list[Finding] = []

        # 1. Typosquatting
        findings.extend(build_typosquat_findings(package.name, package.version))

        # 2. Maintainer trust
        findings.extend(
            analyze_maintainer(package.name, package.version, package.metadata)
        )

        # 3. CVE lookup (async, cached)
        findings.extend(await find_cves(package.name, package.version))

        # 4. Per-file AST + obfuscation analysis (high-priority files first)
        py_files = {k: v for k, v in package.files.items() if k.endswith(".py")}
        ordered = sorted(
            py_files.items(),
            key=lambda kv: (0 if _is_high_priority(kv[0]) else 1),
        )
        for file_path, content in ordered:
            findings.extend(analyze_source(package.name, package.version, file_path, content))
            findings.extend(
                analyze_obfuscation(package.name, package.version, file_path, content)
            )

        return findings


def _is_high_priority(file_path: str) -> bool:
    import os  # noqa: PLC0415

    return os.path.basename(file_path) in _HIGH_PRIORITY
