"""Planes de hipótesis comprobables para el cuaderno de investigación.

La comprobación lógica trabaja sobre efectos candidatos explícitos; no
demuestra por sí sola la calidad científica ni la validez de un contraste.
"""
from dataclasses import asdict, dataclass
from datetime import date
import hashlib
import json
import math


def _text(value, name):
    if not isinstance(value, str) or not value.strip():
        raise ValueError(f'{name} debe ser texto no vacío')
    return value.strip()


def _finite(value, name):
    if isinstance(value, bool) or not isinstance(value, (int, float)):
        raise ValueError(f'{name} debe ser un número finito')
    try:
        converted = float(value)
    except OverflowError as exc:
        raise ValueError(f'{name} debe ser un número finito') from exc
    if not math.isfinite(converted):
        raise ValueError(f'{name} debe ser un número finito')
    return converted


@dataclass(frozen=True)
class ResearchQuestion:
    question: str
    population: str
    intervention: str
    comparator: str

    def __post_init__(self):
        for name in ('question', 'population', 'intervention', 'comparator'):
            object.__setattr__(self, name, _text(getattr(self, name), name))


@dataclass(frozen=True)
class Prediction:
    metric: str
    direction: str
    min_effect: float
    refutation: str
    possible_effects: tuple[float, ...]

    def __post_init__(self):
        object.__setattr__(self, 'metric', _text(self.metric, 'metric'))
        object.__setattr__(self, 'refutation', _text(self.refutation, 'refutation'))
        if self.direction not in ('increase', 'decrease', 'two_sided'):
            raise ValueError('direction debe ser increase, decrease o two_sided')
        size = _finite(self.min_effect, 'min_effect')
        if size <= 0:
            raise ValueError('min_effect debe ser positivo')
        object.__setattr__(self, 'min_effect', size)
        if not isinstance(self.possible_effects, (tuple, list)):
            raise ValueError('possible_effects debe ser una lista o tupla de efectos')
        effects = tuple(_finite(x, 'possible_effects') for x in self.possible_effects)
        if len(set(effects)) < 2:
            raise ValueError('se requieren al menos dos efectos posibles distintos')
        object.__setattr__(self, 'possible_effects', effects)
        statuses = {self.supports(x) for x in effects}
        if statuses != {False, True}:
            raise ValueError('los efectos candidatos deben incluir apoyo y refutación')

    def supports(self, effect):
        """La diferencia es intervención menos comparador, en unidades de metric."""
        value = _finite(effect, 'effect')
        if self.direction == 'increase':
            return value >= self.min_effect
        if self.direction == 'decrease':
            return value <= -self.min_effect
        return abs(value) >= self.min_effect


@dataclass(frozen=True)
class Hypothesis:
    claim: str
    question: ResearchQuestion
    predictions: tuple[Prediction, ...]

    def __post_init__(self):
        object.__setattr__(self, 'claim', _text(self.claim, 'claim'))
        if not isinstance(self.question, ResearchQuestion):
            raise ValueError('question debe ser ResearchQuestion')
        if not isinstance(self.predictions, (tuple, list)) or not self.predictions:
            raise ValueError('predictions debe contener al menos una predicción')
        predictions = tuple(self.predictions)
        if not all(isinstance(p, Prediction) for p in predictions):
            raise ValueError('cada predicción debe ser Prediction')
        object.__setattr__(self, 'predictions', predictions)

    def checks(self):
        """Enumera efectos candidatos y su compatibilidad, sin evaluar incertidumbre."""
        return [[(x, p.supports(x)) for x in p.possible_effects] for p in self.predictions]

    def markdown(self, day):
        """Documento fechado; hash de contenido canónico, no sello temporal externo."""
        if not isinstance(day, str):
            raise ValueError('day debe ser una fecha ISO')
        try:
            parsed = date.fromisoformat(day)
        except ValueError as exc:
            raise ValueError('day debe ser una fecha ISO válida') from exc
        if parsed.isoformat() != day:
            raise ValueError('day debe tener formato AAAA-MM-DD')
        payload = {'date': day, 'hypothesis': asdict(self)}
        canonical = json.dumps(payload, ensure_ascii=False, sort_keys=True, separators=(',', ':'), allow_nan=False)
        digest = hashlib.sha256(canonical.encode('utf-8')).hexdigest()
        q = self.question
        lines = [f'# Plan de hipótesis ({day})', '', f'Pregunta: {q.question}',
                 f'Población: {q.population}', f'Intervención: {q.intervention}',
                 f'Comparación: {q.comparator}', f'Hipótesis: {self.claim}', '']
        for i, p in enumerate(self.predictions, 1):
            lines.extend([f'## Predicción {i}', f'Métrica: {p.metric}',
                          f'Dirección: {p.direction}; magnitud mínima: {p.min_effect}',
                          f'Condición refutadora: {p.refutation}',
                          f'Efectos candidatos: {list(p.possible_effects)}', ''])
        lines.append(f'SHA-256 del contenido canónico: {digest}')
        return '\n'.join(lines)
