"""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)

@dataclass(frozen=True)
class Evidence:
    id: str
    location: str
    description: str
    scope: tuple[str, ...]

    def __post_init__(self):
        for name in ('id', 'location', 'description'):
            object.__setattr__(self, name, _text(getattr(self, name), name))
        if not isinstance(self.scope, (list, tuple)) or not self.scope:
            raise ValueError('scope debe enumerar condiciones no vacías')
        object.__setattr__(self, 'scope', tuple(_text(x, 'scope') for x in self.scope))


@dataclass(frozen=True)
class Claim:
    id: str
    text: str
    scope: tuple[str, ...]
    evidence_ids: tuple[str, ...] = ()
    unsupported_reason: str = ''

    def __post_init__(self):
        for name in ('id', 'text'):
            object.__setattr__(self, name, _text(getattr(self, name), name))
        if not isinstance(self.scope, (list, tuple)) or not self.scope:
            raise ValueError('scope debe enumerar condiciones no vacías')
        object.__setattr__(self, 'scope', tuple(_text(x, 'scope') for x in self.scope))
        if not isinstance(self.evidence_ids, (list, tuple)):
            raise ValueError('evidence_ids debe ser una lista o tupla')
        object.__setattr__(self, 'evidence_ids', tuple(_text(x, 'evidence_id') for x in self.evidence_ids))
        if not isinstance(self.unsupported_reason, str):
            raise ValueError('unsupported_reason debe ser texto')
        if not self.evidence_ids and not self.unsupported_reason.strip():
            raise ValueError('sin evidencia debe declararse el motivo')


@dataclass(frozen=True)
class ClaimEvidenceMap:
    claims: tuple[Claim, ...]
    evidence: tuple[Evidence, ...]

    def __post_init__(self):
        if not all(isinstance(x, Claim) for x in self.claims) or not all(isinstance(x, Evidence) for x in self.evidence):
            raise ValueError('tipos de afirmación o evidencia inválidos')
        cids = [x.id for x in self.claims]; eids = [x.id for x in self.evidence]
        if len(set(cids)) != len(cids) or len(set(eids)) != len(eids):
            raise ValueError('identificadores duplicados')
        if any(ref not in eids for claim in self.claims for ref in claim.evidence_ids):
            raise ValueError('referencia de evidencia desconocida')
        object.__setattr__(self, 'claims', tuple(self.claims))
        object.__setattr__(self, 'evidence', tuple(self.evidence))

    def unsupported(self):
        return [c.id for c in self.claims if not c.evidence_ids]

    def coverage_report(self):
        """Condiciones explícitas por las que no hay evidencia enlazada.

        Cada elemento de scope es un caso concreto; la unión de evidencias
        enlazadas debe cubrir los casos declarados. No verifica causalidad.
        """
        evidence = {e.id:e for e in self.evidence}
        report = {}
        for c in self.claims:
            covered = {case for ref in c.evidence_ids for case in evidence[ref].scope}
            report[c.id] = {'without_evidence': not c.evidence_ids,
                            'uncovered_scope': sorted(set(c.scope) - covered)}
        return report


@dataclass(frozen=True)
class ReadingCard:
    title: str
    citation: str
    question: str
    contribution: str
    limitations: str
    claim_map: ClaimEvidenceMap

    def __post_init__(self):
        for name in ('title','citation','question','contribution','limitations'):
            object.__setattr__(self, name, _text(getattr(self, name), name))
        if not isinstance(self.claim_map, ClaimEvidenceMap):
            raise ValueError('claim_map inválido')

    def to_markdown(self):
        def clean(value): return value.replace('\n',' ').replace('|','\\|')
        lines = [f'# {self.title}', '', f'Fuente: {self.citation}', '',
                 f'Pregunta: {self.question}', '', f'Contribución: {self.contribution}', '',
                 f'Límites: {self.limitations}', '', '| Afirmación | Evidencia | Alcance sin cubrir |', '|---|---|---|']
        report = self.claim_map.coverage_report()
        evidence = {e.id:e for e in self.claim_map.evidence}
        for c in self.claim_map.claims:
            refs = '; '.join(evidence[r].location for r in c.evidence_ids) or c.unsupported_reason
            missing = ', '.join(report[c.id]['uncovered_scope']) or 'ninguno declarado'
            lines.append(f'| {clean(c.text)} | {clean(refs)} | {clean(missing)} |')
        return '\n'.join(lines)

    def literature_row(self):
        return {'title':self.title, 'citation':self.citation, 'question':self.question,
                'contribution':self.contribution, 'limitations':self.limitations,
                'unsupported_claims':self.claim_map.unsupported()}

@dataclass(frozen=True)
class ExperimentPlan:
    question: str
    hypothesis: str
    unit: str
    factors: tuple[str, ...]
    blocks: tuple[str, ...]
    metrics: tuple[str, ...]
    analysis: str
    seeds: tuple[int, ...]
    decision: str
    date: str

    def __post_init__(self):
        for name in ('question','hypothesis','unit','analysis','decision'):
            object.__setattr__(self,name,_text(getattr(self,name),name))
        for name in ('factors','blocks','metrics'):
            values=getattr(self,name)
            if not isinstance(values,(list,tuple)) or not values:
                raise ValueError(f'{name} necesita una lista no vacía')
            object.__setattr__(self,name,tuple(_text(v,name) for v in values))
        if not isinstance(self.seeds,(list,tuple)) or not self.seeds or any(isinstance(s,bool) or not isinstance(s,int) for s in self.seeds):
            raise ValueError('seeds debe contener enteros')
        if len(set(self.seeds)) != len(self.seeds): raise ValueError('semillas repetidas')
        object.__setattr__(self,'seeds',tuple(self.seeds))
        try: parsed=date.fromisoformat(self.date)
        except (ValueError,TypeError) as exc: raise ValueError('fecha ISO inválida') from exc
        if parsed.isoformat()!=self.date: raise ValueError('fecha debe ser AAAA-MM-DD')

    def markdown(self):
        payload=asdict(self); canonical=json.dumps(payload,ensure_ascii=False,sort_keys=True,separators=(',',':'),allow_nan=False)
        digest=hashlib.sha256(canonical.encode('utf8')).hexdigest()
        lines=[f'# Plan experimental ({self.date})',f'Pregunta: {self.question}',f'Hipótesis: {self.hypothesis}',f'Unidad: {self.unit}',
               f'Factores: {", ".join(self.factors)}',f'Bloques: {", ".join(self.blocks)}',f'Métricas: {", ".join(self.metrics)}',
               f'Análisis: {self.analysis}',f'Semillas: {", ".join(map(str,self.seeds))}',f'Decisión: {self.decision}',
               f'SHA-256 del contenido canónico: {digest}']
        return '\n\n'.join(lines)


def seeds_for_se(sd, target_se):
    """Tamaño aproximado para SE de una media con unidades independientes."""
    sd=_finite(sd,'sd');target_se=_finite(target_se,'target_se')
    if sd<0 or target_se<=0: raise ValueError('sd no negativa y target_se positivo')
    return max(1,math.ceil((sd/target_se)**2))


def variance_components(results):
    """ANOVA anidado equilibrado partición > semilla; varianzas truncadas en cero."""
    import numpy as np
    x=np.asarray(results,dtype=float)
    if x.ndim!=2 or min(x.shape)<2 or not np.isfinite(x).all(): raise ValueError('matriz finita de al menos 2 x 2')
    a,b=x.shape; means=x.mean(axis=1);grand=x.mean()
    ms_between=b*np.sum((means-grand)**2)/(a-1)
    ms_within=np.sum((x-means[:,None])**2)/(a*(b-1))
    raw=(ms_between-ms_within)/b
    return {'partition':float(max(0,raw)), 'within':float(ms_within),
            'partition_raw':float(raw),'between_ms':float(ms_between)}
