# retoor <retoor@molodetz.nl>
from __future__ import annotations

from dataclasses import dataclass, field
from pathlib import Path
from typing import Any, Callable

from devplacepy.services.jobs.isslop.analysis.metrics import FileMetrics

SEVERITY_STRONG: str = "strong"
SEVERITY_MEDIUM: str = "medium"
SEVERITY_WEAK: str = "weak"

AXIS_ORIGIN: str = "origin"
AXIS_QUALITY: str = "quality"

SEVERITY_FACTORS: dict[str, float] = {
    SEVERITY_STRONG: 1.0,
    SEVERITY_MEDIUM: 0.6,
    SEVERITY_WEAK: 0.3,
}


@dataclass(frozen=True)
class Signal:
    code: str
    title: str
    severity: str
    axis: str
    weight: float
    line: int
    evidence: str

    def to_dict(self) -> dict[str, Any]:
        return {
            "code": self.code,
            "title": self.title,
            "severity": self.severity,
            "axis": self.axis,
            "weight": self.weight,
            "line": self.line,
            "evidence": self.evidence[:200],
        }


@dataclass(frozen=True)
class RepoContext:
    root: Path
    python_dependencies: frozenset[str]
    javascript_dependencies: frozenset[str]
    local_python_modules: frozenset[str]
    has_python_manifest: bool
    has_javascript_manifest: bool
    javascript_alias_prefixes: frozenset[str] = frozenset()


@dataclass
class FileContext:
    path: Path
    relative: str
    language: str
    text: str
    lines: list[str] = field(default_factory=list)
    comments: list[tuple[int, str]] = field(default_factory=list)
    metrics: FileMetrics | None = None
    repo: RepoContext | None = None
    fingerprint_only: bool = False


Detector = Callable[[FileContext], list[Signal]]


def run_detectors(context: FileContext, detectors: list[Detector]) -> list[Signal]:
    findings: list[Signal] = []
    for detector in detectors:
        findings.extend(detector(context))
    return findings
