"""Generate human questions and answers from platform reports."""

from __future__ import annotations

from dataclasses import dataclass
from typing import Sequence

from .catalog import HUMAN_PROFILES, PROFILE_BY_ID
from .models import MatrixCell, PlatformHumanReport, as_plain_data, score_label


@dataclass(slots=True)
class HumanQuestion:
    question_id: str
    platform_id: str
    profile_id: str
    question: str
    answer: str
    confidence: str
    evidence: tuple[str, ...]
    next_action: str

    def to_dict(self) -> dict[str, object]:
        return as_plain_data(self)


def confidence_for_score(score: int) -> str:
    if score >= 80:
        return "alta"
    if score >= 55:
        return "media"
    if score >= 30:
        return "baixa"
    return "muito_baixa"


def answer_for_cell(report: PlatformHumanReport, cell: MatrixCell, question: str) -> str:
    profile = PROFILE_BY_ID[cell.profile_id]
    if cell.score >= 75:
        return (
            f"Para {profile.name}, {report.platform.title} ja mostra atendimento {score_label(cell.score)}. "
            f"A leitura atual e: {cell.explanation}"
        )
    if cell.score >= 45:
        return (
            f"Para {profile.name}, {report.platform.title} oferece base parcial. "
            "A proxima etapa e transformar as evidencias tecnicas em telas, relatorios ou comandos humanos."
        )
    return (
        f"Para {profile.name}, {report.platform.title} ainda nao responde bem a pergunta '{question}'. "
        "A plataforma precisa de evidencia, fluxo ou relatorio orientado a esse perfil."
    )


def next_action_for_cell(cell: MatrixCell) -> str:
    if cell.gaps:
        return cell.gaps[0]
    if cell.score < 75:
        return "Criar melhoria humana especifica para o perfil."
    return "Manter evidencia e revalidar periodicamente."


def questions_for_report(report: PlatformHumanReport, max_per_profile: int = 2) -> tuple[HumanQuestion, ...]:
    output: list[HumanQuestion] = []
    cells_by_profile = {cell.profile_id: cell for cell in report.cells}
    for profile in HUMAN_PROFILES:
        cell = cells_by_profile.get(profile.profile_id)
        if cell is None:
            continue
        for index, question in enumerate(profile.typical_questions[:max_per_profile], start=1):
            output.append(
                HumanQuestion(
                    question_id=f"{report.platform.platform_id}-{profile.profile_id}-{index}",
                    platform_id=report.platform.platform_id,
                    profile_id=profile.profile_id,
                    question=question,
                    answer=answer_for_cell(report, cell, question),
                    confidence=confidence_for_score(cell.score),
                    evidence=cell.evidence_refs[:5],
                    next_action=next_action_for_cell(cell),
                )
            )
    return tuple(output)


def questions_for_ecosystem(reports: Sequence[PlatformHumanReport]) -> tuple[HumanQuestion, ...]:
    questions: list[HumanQuestion] = []
    for report in reports:
        questions.extend(questions_for_report(report))
    return tuple(questions)


def questions_markdown(questions: Sequence[HumanQuestion]) -> str:
    lines = ["# Perguntas humanas respondidas", ""]
    for question in questions:
        lines.append(f"## {question.question}")
        lines.append("")
        lines.append(f"- plataforma: `{question.platform_id}`")
        lines.append(f"- perfil: `{question.profile_id}`")
        lines.append(f"- confianca: `{question.confidence}`")
        lines.append("")
        lines.append(question.answer)
        lines.append("")
        lines.append("Proxima acao: " + question.next_action)
        if question.evidence:
            lines.append("")
            lines.append("Evidencias:")
            for evidence in question.evidence:
                lines.append(f"- `{evidence}`")
        lines.append("")
    return "\n".join(lines).strip() + "\n"


def unanswered_questions(questions: Sequence[HumanQuestion]) -> tuple[HumanQuestion, ...]:
    return tuple(question for question in questions if question.confidence in {"baixa", "muito_baixa"})


def question_index(questions: Sequence[HumanQuestion]) -> dict[str, list[str]]:
    result: dict[str, list[str]] = {}
    for question in questions:
        result.setdefault(question.profile_id, []).append(question.question_id)
    return result

