from __future__ import annotations

import re
from typing import Sequence

from .models import TaskResult

ANSI_RE = re.compile(r"\x1b\[[0-?]*[ -/]*[@-~]")
SCORE_PREFIXES = ("Score Lynis", "Hardening index")
RECOMMENDATION_PREFIXES = (
    "Modifications recommandées",
    "•",
)


def clean_text(text: str) -> str:
    return ANSI_RE.sub("", text)


def collect_details(results: Sequence[TaskResult]) -> tuple[list[str], list[str]]:
    score_lines: list[str] = []
    recommendation_lines: list[str] = []
    seen_scores: set[str] = set()
    seen_recommendations: set[str] = set()

    for result in results:
        for detail in result.details:
            line = clean_text(detail).strip()
            if not line:
                continue

            if any(line.startswith(prefix) for prefix in SCORE_PREFIXES) and line not in seen_scores:
                seen_scores.add(line)
                score_lines.append(line)
                continue

            if any(line.startswith(prefix) for prefix in RECOMMENDATION_PREFIXES) and line not in seen_recommendations:
                seen_recommendations.add(line)
                recommendation_lines.append(line)

    return score_lines, recommendation_lines
