from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
from typing import Optional

from . import tough_classes as ta


@dataclass
class RunResult:
    case_dir: Path
    ok: bool
    error: Optional[str] = None


def run_case(case_dir: str | Path, *, mode: str = "all") -> RunResult:
    """
    mode:
      - all: reader.write_all()
      - eleme_conne: reader.write_eleme_conne()
      - geometry: reader.write_geometry()
      - incon: reader.write_incon()
      - result: reader.write_result()
    """
    case_dir = Path(case_dir).expanduser().resolve()

    try:
        reader = ta.vis_reader(str(case_dir))

        if mode == "all":
            reader.write_all()
        elif mode == "eleme_conne":
            reader.write_eleme_conne()
        elif mode == "geometry":
            reader.write_geometry()
        elif mode == "incon":
            reader.write_incon()
        elif mode == "result":
            reader.write_result()
        else:
            raise ValueError(f"Unknown mode: {mode}")

        return RunResult(case_dir=case_dir, ok=True)
    except Exception as e:
        return RunResult(case_dir=case_dir, ok=False, error=f"{type(e).__name__}: {e}")