"""params.yaml <-> AnalysisParams (analysis spec 3.1). Unknown keys and wrong types are refused by name."""
from __future__ import annotations

import dataclasses
import re
from dataclasses import dataclass
from pathlib import Path

import yaml

METRICS = ("syn_per_um2", "syn_per_um3", "n_synapse", "n_synapse_maxplane")
FIGURE_FORMATS = ("png", "svg")


class ParamsError(ValueError):
    pass


@dataclass(frozen=True)
class InputRun:
    stem: str
    run_id: str
    quality: str = "good"
    notes: str = ""               # the sheet's notes for the stack, so a note-based exclusion is reproducible from params.yaml
    group: str = ""               # the subjects key: blinded group (A/B) and preferred paw of the stack's rat, "" when unknown
    paw: str = ""


@dataclass(frozen=True)
class BehaviourRow:
    """Reaching success of one rat (from the stack database's behaviour table), carried so the folder re-runs alone."""
    animal: str
    n_sessions: int
    success_total: int
    reaches_total: int
    success_rate: float
    success_first3: float
    success_last3: float
    success_gain: float


@dataclass(frozen=True)
class StackFilter:
    quality: tuple = ("good",)
    exclude_note_regex: str = ""        # stacks whose sheet notes match (case-insensitive) are excluded; "" = no note filter


@dataclass(frozen=True)
class SomaFilter:
    volume_min_um3: float = 300.0
    volume_max_um3: float = 6000.0
    border_fraction_max: float = 0.1
    exclude_touches_border: bool = True
    neun_mean_min: float = 0.0
    require_tail: bool = False          # keep only somas with a dendritic tail (has_tail from the tails stage)


@dataclass(frozen=True)
class SplitParams:
    enabled: bool = True
    k: int = 2
    n_bootstrap: int = 200
    min_subjects: int = 4
    random_seed: int = 0
    balanced: bool = True        # the study's two groups are (near-)equal in size: cluster sizes are constrained
    max_size_difference: int = 1  # ... to differ by at most this many subjects (1 = as equal as n allows)


@dataclass(frozen=True)
class GainCorrection:
    enabled: bool = False
    metric: str = "n_synapse_maxplane"   # the pipeline column compared with the raters' clicks per labelled neuron
    min_neurons: int = 10                # a rat with fewer labelled neurons keeps gain 1 (computed, not applied)


@dataclass(frozen=True)
class GroupsParams:
    enabled: bool = True
    n_permutations: int = 10000
    random_seed: int = 0


@dataclass(frozen=True)
class AnalysisParams:
    analysis_id: str = ""
    label: str = ""
    created: str = ""
    code_version: str = ""
    dataset: str = ""
    inputs: tuple = ()
    behaviour: tuple = ()              # one BehaviourRow per rat with reaching data among the inputs
    stack_filter: StackFilter = StackFilter()
    soma_filter: SomaFilter = SomaFilter()
    metrics: tuple = METRICS
    split: SplitParams = SplitParams()
    figure_format: tuple = FIGURE_FORMATS
    gain_correction: GainCorrection = GainCorrection()
    groups: GroupsParams = GroupsParams()

    def validate(self) -> None:
        sf, sp = self.soma_filter, self.split
        checks = [
            (sf.volume_min_um3 < sf.volume_max_um3, "soma_filter.volume_min_um3 must be below volume_max_um3"),
            (sf.volume_min_um3 >= 0, "soma_filter.volume_min_um3 must be >= 0"),
            (0 <= sf.border_fraction_max <= 1, "soma_filter.border_fraction_max must be within [0, 1]"),
            (sp.k >= 2, "split.k must be >= 2"),
            (sp.n_bootstrap >= 0, "split.n_bootstrap must be >= 0"),
            (sp.min_subjects >= 2, "split.min_subjects must be >= 2"),
            (len(self.metrics) > 0 and all(m in METRICS for m in self.metrics), f"metrics must be a non-empty subset of {list(METRICS)}"),
            (len(self.figure_format) > 0 and all(f in FIGURE_FORMATS for f in self.figure_format),
             f"figure_format must be a non-empty subset of {list(FIGURE_FORMATS)}"),
            (len(self.stack_filter.quality) > 0, "stack_filter.quality must name at least one quality"),
            (sp.max_size_difference >= 1, "split.max_size_difference must be >= 1"),
            (self.gain_correction.min_neurons >= 1, "gain_correction.min_neurons must be >= 1"),
            (self.gain_correction.metric in METRICS, f"gain_correction.metric must be one of {list(METRICS)}"),
            (self.groups.n_permutations >= 100, "groups.n_permutations must be >= 100"),
        ]
        for ok, msg in checks:
            if not ok:
                raise ParamsError(msg)
        try:
            re.compile(self.stack_filter.exclude_note_regex)
        except re.error as e:
            raise ParamsError(f"stack_filter.exclude_note_regex is not a valid regular expression: {e}")


# field name -> kind: a scalar kind name, "list_str", "inputs"/"behaviour" (lists of rows), or a nested dataclass
_KINDS = {
    AnalysisParams: {"analysis_id": "str", "label": "str", "created": "str", "code_version": "str", "dataset": "str",
                     "inputs": "inputs", "behaviour": "behaviour", "stack_filter": StackFilter, "soma_filter": SomaFilter, "metrics": "list_str",
                     "split": SplitParams, "figure_format": "list_str", "gain_correction": GainCorrection, "groups": GroupsParams},
    StackFilter: {"quality": "list_str", "exclude_note_regex": "str"},
    SomaFilter: {"volume_min_um3": "float", "volume_max_um3": "float", "border_fraction_max": "float",
                 "exclude_touches_border": "bool", "neun_mean_min": "float", "require_tail": "bool"},
    SplitParams: {"enabled": "bool", "k": "int", "n_bootstrap": "int", "min_subjects": "int", "random_seed": "int", "balanced": "bool",
                  "max_size_difference": "int"},
    InputRun: {"stem": "str", "run_id": "str", "quality": "str", "notes": "str", "group": "str", "paw": "str"},
    BehaviourRow: {"animal": "str", "n_sessions": "int", "success_total": "int", "reaches_total": "int", "success_rate": "float",
                   "success_first3": "float", "success_last3": "float", "success_gain": "float"},
    GainCorrection: {"enabled": "bool", "metric": "str", "min_neurons": "int"},
    GroupsParams: {"enabled": "bool", "n_permutations": "int", "random_seed": "int"},
}


def _scalar(kind: str, v, path: str):
    if kind == "bool":
        if isinstance(v, bool):
            return v
    elif kind == "int":
        if isinstance(v, int) and not isinstance(v, bool):
            return v
    elif kind == "float":
        if isinstance(v, (int, float)) and not isinstance(v, bool):
            return float(v)
    elif kind == "str":
        if isinstance(v, str):
            return v
    elif kind == "list_str":
        if isinstance(v, (list, tuple)) and all(isinstance(x, str) for x in v):
            return tuple(v)
        raise ParamsError(f"{path}: expected a list of strings")
    raise ParamsError(f"{path}: expected {kind}, got {type(v).__name__}")


def _build(cls, d, path: str):
    if not isinstance(d, dict):
        raise ParamsError(f"{path or 'params'}: not a mapping")
    kinds = _KINDS[cls]
    for k in d:
        if k not in kinds:
            raise ParamsError(f"{path}{k}: unknown key")
    values = {}
    for name, kind in kinds.items():
        if name not in d:
            continue
        v, here = d[name], f"{path}{name}"
        if kind in ("inputs", "behaviour"):
            if not isinstance(v, (list, tuple)):
                raise ParamsError(f"{here}: expected a list")
            row_cls = InputRun if kind == "inputs" else BehaviourRow
            values[name] = tuple(_build(row_cls, x, f"{here}[{i}].") for i, x in enumerate(v))
        elif isinstance(kind, type):
            values[name] = _build(kind, v, f"{here}.")
        else:
            values[name] = _scalar(kind, v, here)
    missing = [f.name for f in dataclasses.fields(cls) if f.default is dataclasses.MISSING and f.name not in values]
    if missing:
        raise ParamsError(f"{path}{missing[0]}: required")
    return cls(**values)


def from_dict(d) -> AnalysisParams:
    return _build(AnalysisParams, d, "")


def _plain(v):
    if dataclasses.is_dataclass(v):
        return {f.name: _plain(getattr(v, f.name)) for f in dataclasses.fields(v)}
    if isinstance(v, (list, tuple)):
        return [_plain(x) for x in v]
    return v


def to_dict(p: AnalysisParams) -> dict:
    return _plain(p)


def load(path) -> AnalysisParams:
    return from_dict(yaml.safe_load(Path(path).read_text()) or {})


def dump(p: AnalysisParams, path) -> None:
    Path(path).write_text(yaml.safe_dump(to_dict(p), sort_keys=False, default_flow_style=False))
