from __future__ import annotations

import random
from dataclasses import dataclass
from typing import Dict, Tuple

import numpy as np
import pandas as pd
import torch
import torch.nn as nn

from .config import SuiteConfig

try:
    from tqdm.auto import tqdm
except ImportError:
    class tqdm:  # type: ignore
        def __init__(self, *args, **kwargs): pass
        def update(self, n=1): pass
        def set_postfix(self, *args, **kwargs): pass
        def __enter__(self): return self
        def __exit__(self, *args): return False


def seed_everything(seed: int) -> None:
    random.seed(seed)
    np.random.seed(seed)
    torch.manual_seed(seed)
    if torch.cuda.is_available():
        torch.cuda.manual_seed(seed)
        torch.cuda.manual_seed_all(seed)
    torch.backends.cudnn.deterministic = True
    torch.backends.cudnn.benchmark = False


def get_device() -> torch.device:
    return torch.device("cuda" if torch.cuda.is_available() else "cpu")


class MultiTaskNet(nn.Module):
    def __init__(
        self,
        d_in: int,
        config: SuiteConfig,
        anchor_low_norm: float = 0.0,
    ) -> None:
        super().__init__()
        layers = []
        d = d_in
        for hidden in config.trunk:
            layers.extend(
                [
                    nn.Linear(d, hidden),
                    nn.BatchNorm1d(hidden),
                    nn.ReLU(),
                    nn.Dropout(config.dropout),
                ]
            )
            d = hidden
        self.trunk = nn.Sequential(*layers)
        self.reg_head = nn.Sequential(
            nn.Linear(d, config.head), nn.ReLU(), nn.Linear(config.head, 1)
        )
        self.cls_head = nn.Sequential(
            nn.Linear(d, config.head), nn.ReLU(), nn.Linear(config.head, 1)
        )
        self.anchor_low = nn.Parameter(torch.tensor(float(anchor_low_norm)))

    def forward(self, x: torch.Tensor):
        z = self.trunk(x)
        reg = self.reg_head(z)
        logit = self.cls_head(z)
        p = torch.sigmoid(logit)
        blended = p * self.anchor_low + (1.0 - p) * reg
        return reg, logit, p, blended


def effective_number_weights(
    y_binary: np.ndarray,
    beta: float,
) -> Tuple[np.ndarray, float, float]:
    y = np.asarray(y_binary, dtype=np.float32)
    n_low = float(y.sum())
    n_high = float(len(y) - n_low)
    if n_low == 0 or n_high == 0:
        low = high = 1.0
    else:
        raw_low = (1.0 - beta) / (1.0 - beta ** n_low)
        raw_high = (1.0 - beta) / (1.0 - beta ** n_high)
        normalizer = (n_low * raw_low + n_high * raw_high) / (n_low + n_high)
        low = raw_low / normalizer
        high = raw_high / normalizer
    weights = np.where(y > 0.5, low, high).astype(np.float32)
    weights /= max(float(weights.mean()), 1e-12)
    return weights, float(low), float(high)


@dataclass
class PredictionResult:
    blended_grade: np.ndarray
    classification_score: np.ndarray
    diagnostics: Dict[str, float]


def train_predict(
    X_train: pd.DataFrame,
    y_train: np.ndarray,
    X_test: pd.DataFrame,
    config: SuiteConfig,
    desc: str = "",
) -> PredictionResult:
    seed_everything(config.seed)
    device = get_device()
    Xtr = X_train.to_numpy(dtype=np.float32)
    Xte = X_test.to_numpy(dtype=np.float32)

    mu = Xtr.mean(axis=0)
    sd = Xtr.std(axis=0)
    sd[~np.isfinite(sd) | (sd == 0)] = 1.0
    Xtr = (Xtr - mu) / sd
    Xte = (Xte - mu) / sd

    y = np.asarray(y_train, dtype=float)
    ym = float(y.mean())
    ys = float(y.std()) or 1.0
    yz = ((y - ym) / ys).astype(np.float32)
    yb = (y < config.event).astype(np.float32)

    cls_w, cb_low, cb_high = effective_number_weights(yb, config.cb_beta)
    reg_w = np.where(yb > 0.5, config.low_weight, 1.0).astype(np.float32)
    reg_w /= max(float(reg_w.mean()), 1e-12)

    low_values = y[y < config.event]
    anchor_raw = float(low_values.mean()) if low_values.size else config.event / 2.0
    anchor_low_norm = (anchor_raw - ym) / ys

    Xtr_t = torch.from_numpy(Xtr).to(device)
    yz_t = torch.from_numpy(yz).view(-1, 1).to(device)
    yb_t = torch.from_numpy(yb).view(-1, 1).to(device)
    reg_w_t = torch.from_numpy(reg_w).view(-1, 1).to(device)
    cls_w_t = torch.from_numpy(cls_w).view(-1, 1).to(device)

    model = MultiTaskNet(Xtr.shape[1], config, anchor_low_norm).to(device)
    optimizer = torch.optim.AdamW(
        model.parameters(),
        lr=config.learning_rate,
        weight_decay=config.weight_decay,
    )
    bce = nn.BCEWithLogitsLoss(reduction="none")

    n = len(Xtr_t)
    n_batches = (n + config.batch_size - 1) // config.batch_size
    with tqdm(
        total=config.epochs * n_batches,
        desc=f"train {desc}".strip(),
        leave=False,
    ) as bar:
        for epoch in range(config.epochs):
            permutation = torch.randperm(n, device=device)
            model.train()
            running = 0.0
            steps = 0
            for start in range(0, n, config.batch_size):
                idx = permutation[start : start + config.batch_size]
                bar.update(1)
                if len(idx) < 2:
                    continue
                optimizer.zero_grad()
                reg, logit, _, blended = model(Xtr_t[idx])
                l_reg = (reg_w_t[idx] * (reg - yz_t[idx]) ** 2).mean()
                l_cls = (cls_w_t[idx] * bce(logit, yb_t[idx])).mean()
                l_blend = (reg_w_t[idx] * (blended - yz_t[idx]) ** 2).mean()
                loss = (
                    config.w_reg * l_reg
                    + config.w_cls * l_cls
                    + config.w_blend * l_blend
                )
                loss.backward()
                optimizer.step()
                running += float(loss.item())
                steps += 1
            bar.set_postfix(epoch=epoch + 1, loss=f"{running / max(steps, 1):.4f}")

    model.eval()
    Xte_t = torch.from_numpy(Xte)
    blended_parts = []
    cls_parts = []
    with torch.no_grad():
        for start in range(0, len(Xte_t), config.prediction_batch_size):
            xb = Xte_t[start : start + config.prediction_batch_size].to(device)
            _, _, p, blended = model(xb)
            blended_parts.append(blended.view(-1).cpu())
            cls_parts.append(p.view(-1).cpu())
    blended_grade = torch.cat(blended_parts).numpy() * ys + ym
    classification_score = torch.cat(cls_parts).numpy()
    diagnostics = {
        "n_low": float(yb.sum()),
        "n_high": float(len(yb) - yb.sum()),
        "cb_low": cb_low,
        "cb_high": cb_high,
        "cb_ratio": cb_low / max(cb_high, 1e-12),
        "feature_count": float(Xtr.shape[1]),
        "anchor_low_raw": anchor_raw,
    }
    return PredictionResult(blended_grade, classification_score, diagnostics)
