from __future__ import annotations
from dataclasses import dataclass, field, asdict
from typing import Any

SEVERITIES = ("good", "normal", "notgood", "bad", "serious", "info")
SEVERITY_LABELS = {
    "good": "Good",
    "normal": "Normal",
    "notgood": "Not Good",
    "bad": "Bad",
    "serious": "Serious",
    "info": "Info",
}
SEVERITY_COLORS = {
    "good": "bright-green",
    "normal": "bright-yellow",
    "notgood": "bright-orange",
    "bad": "bright-red",
    "serious": "magenta",
    "info": "tx-alt",
}


@dataclass
class Finding:
    category: str
    title: str
    detail: str = ""
    severity: str = "info"
    weight: int = 0

    def to_dict(self) -> dict[str, Any]:
        d = asdict(self)
        d["severity_label"] = SEVERITY_LABELS.get(self.severity, self.severity)
        d["color"] = SEVERITY_COLORS.get(self.severity, "tx")
        return d


@dataclass
class ScanResult:
    target: str
    host: str
    port: int
    started_at: float
    finished_at: float = 0.0
    findings: list[Finding] = field(default_factory=list)
    data: dict[str, Any] = field(default_factory=dict)
    rank: str = ""
    score: float = 0.0
    error: str | None = None

    def add(self, f: Finding) -> None:
        self.findings.append(f)

    def to_dict(self) -> dict[str, Any]:
        return {
            "target": self.target,
            "host": self.host,
            "port": self.port,
            "started_at": self.started_at,
            "finished_at": self.finished_at,
            "duration": max(0.0, self.finished_at - self.started_at),
            "findings": [f.to_dict() for f in self.findings],
            "data": self.data,
            "rank": self.rank,
            "score": self.score,
            "error": self.error,
        }


@dataclass
class ProgressMessage:
    phase: str
    detail: str
    progress: float
    severity: str = "info"
    finding: dict[str, Any] | None = None

    def to_dict(self) -> dict[str, Any]:
        return {
            "phase": self.phase,
            "detail": self.detail,
            "progress": self.progress,
            "severity": self.severity,
            "finding": self.finding,
        }
