# Usage:
# from warp_md.analysis.surf import surf, molsurf
# areas = surf(traj, system, mask=":1-10")

from __future__ import annotations

from typing import Optional, Sequence, Union

import numpy as np


MaskLike = Union[str, Sequence[int], np.ndarray]


def _all_resid_mask(system) -> str:
    if not hasattr(system, "atom_table"):
        return "all"
    atoms = system.atom_table()
    resids = atoms.get("resid", [])
    if not resids:
        return "resid 0:0"
    return f"resid {min(resids)}:{max(resids)}"


def _selection_indices(system, mask: MaskLike) -> np.ndarray:
    if isinstance(mask, np.ndarray):
        return np.asarray(mask, dtype=np.int64).reshape(-1)
    if isinstance(mask, (list, tuple)):
        return np.asarray([int(x) for x in mask], dtype=np.int64)
    if mask in ("", "*", "all", None):
        sel = system.select(_all_resid_mask(system))
    else:
        sel = system.select(mask)
    return np.asarray(list(sel.indices), dtype=np.int64)


def _read_all(traj, chunk_frames: Optional[int]):
    max_chunk = chunk_frames or 128
    coords_list = []
    chunk = traj.read_chunk(max_chunk)
    if chunk is None:
        return None
    while chunk is not None:
        coords_list.append(np.asarray(chunk["coords"], dtype=np.float64))
        chunk = traj.read_chunk(max_chunk)
    coords = np.concatenate(coords_list, axis=0) if coords_list else np.empty((0, 0, 3))
    return coords


def _apply_frame_indices(coords, frame_indices: Optional[Sequence[int]]):
    if frame_indices is None:
        return coords
    n_frames = coords.shape[0]
    select = []
    for i in frame_indices:
        j = int(i)
        if j < 0:
            j = n_frames + j
        if 0 <= j < n_frames:
            select.append(j)
    return coords[select]


def _bbox_area(coords: np.ndarray, idx: np.ndarray) -> np.ndarray:
    n_frames = coords.shape[0]
    out = np.zeros((n_frames,), dtype=np.float32)
    if idx.size == 0:
        return out
    for f in range(n_frames):
        sel = coords[f, idx, :]
        if sel.size == 0:
            out[f] = 0.0
            continue
        min_v = sel.min(axis=0)
        max_v = sel.max(axis=0)
        dx, dy, dz = (max_v - min_v).clip(min=0.0)
        out[f] = float(2.0 * (dx * dy + dy * dz + dx * dz))
    return out


def surf(
    traj,
    system,
    mask: MaskLike = "",
    frame_indices: Optional[Sequence[int]] = None,
    chunk_frames: Optional[int] = None,
    device: str = "auto",
) -> np.ndarray:
    """Bounding-box surface area."""
    use_plan = False
    try:
        from warp_md import SurfPlan  # type: ignore

        use_plan = getattr(SurfPlan, "__name__", "") != "_Missing"
    except Exception:
        SurfPlan = None  # type: ignore

    if use_plan and SurfPlan is not None:
        if isinstance(mask, str):
            sel = system.select(mask if mask not in ("", "*", "all", None) else _all_resid_mask(system))
        else:
            sel = system.select_indices(np.asarray(mask, dtype=np.int64).reshape(-1).tolist())
        plan = SurfPlan(sel)
        out = plan.run(traj, system, chunk_frames=chunk_frames, device=device)
        return np.asarray(out, dtype=np.float32)

    coords = _read_all(traj, chunk_frames)
    if coords is None:
        raise ValueError("trajectory has no frames")
    if coords.size == 0:
        return np.empty((0,), dtype=np.float32)
    coords = _apply_frame_indices(coords, frame_indices)
    if coords.size == 0:
        return np.empty((0,), dtype=np.float32)
    idx = _selection_indices(system, mask)
    return _bbox_area(coords, idx)


def molsurf(*args, **kwargs) -> np.ndarray:
    return surf(*args, **kwargs)


__all__ = ["surf", "molsurf"]
