from __future__ import annotations

from dataclasses import dataclass
from pathlib import Path
from typing import List, Optional

from .sbom import ParsedSbomFile, parse_sbom_file


@dataclass
class DiscoveryResult:
    project_root: Path
    sbom_found: bool
    sbom_files: List[ParsedSbomFile]
    has_security_md: bool
    has_docs_security_section: bool
    has_dependabot: bool


def discover_project(project_root: Path, explicit_sbom: Optional[Path] = None) -> DiscoveryResult:
    root = project_root.resolve()

    sbom_files: list[ParsedSbomFile] = []
    if explicit_sbom:
        parsed = parse_sbom_file(explicit_sbom)
        if parsed:
            sbom_files.append(parsed)
    else:
        for path in root.rglob("*"):
            if not path.is_file():
                continue
            if path.suffix.lower() in {".json", ".xml", ".spdx"} and any(
                token in path.name.lower() for token in ("sbom", "bom", "cyclonedx", "spdx")
            ):
                parsed = parse_sbom_file(path)
                if parsed:
                    sbom_files.append(parsed)

    # Simple signals for practices
    has_security_md = (root / "SECURITY.md").is_file()
    has_dependabot = (root / ".github" / "dependabot.yml").is_file()

    has_docs_security_section = False
    docs_root = root / "docs"
    if docs_root.is_dir():
        for md in docs_root.rglob("*.md"):
            text = md.read_text(encoding="utf-8", errors="ignore").lower()
            if "security" in text or "vulnerability" in text:
                has_docs_security_section = True
                break

    return DiscoveryResult(
        project_root=root,
        sbom_found=len(sbom_files) > 0,
        sbom_files=sbom_files,
        has_security_md=has_security_md,
        has_docs_security_section=has_docs_security_section,
        has_dependabot=has_dependabot,
    )

