from __future__ import annotations

import hashlib

from app.agents.schemas.learning import PatternCandidate, SkillCandidate


class SkillCandidateBuilder:
    def build(self, patterns: list[PatternCandidate]) -> list[SkillCandidate]:
        candidates: list[SkillCandidate] = []

        for pattern in patterns:
            if pattern.confidence < 0.55:
                continue

            name = self._build_name(pattern)
            candidates.append(
                SkillCandidate(
                    candidate_id=f"candidate-{self._stable_suffix(pattern)}",
                    name=name,
                    summary=pattern.description,
                    candidate_type=self._map_candidate_type(pattern.pattern_type),
                    source_pattern_ids=[pattern.pattern_id],
                    confidence=pattern.confidence,
                    evidence_refs=pattern.evidence_refs[:4],
                    recommended_status="candidate",
                )
            )

        return candidates

    @staticmethod
    def _build_name(pattern: PatternCandidate) -> str:
        prefix = {
            "workflow": "workflow",
            "decomposition": "decomposition",
            "preference": "preference",
        }.get(pattern.pattern_type, "learned")
        stable_suffix = SkillCandidateBuilder._stable_suffix(pattern)
        return f"{prefix}-{stable_suffix}"

    @staticmethod
    def _map_candidate_type(pattern_type: str) -> str:
        mapping = {
            "workflow": "workflow_skill",
            "decomposition": "decomposition_skill",
            "preference": "preference_skill",
        }
        return mapping.get(pattern_type, "workflow_skill")

    @staticmethod
    def _stable_suffix(pattern: PatternCandidate) -> str:
        raw = f"{pattern.pattern_type}:{pattern.description}".encode("utf-8")
        return hashlib.sha1(raw).hexdigest()[:10]
