from __future__ import annotations

from contextlib import contextmanager
from dataclasses import dataclass
import json
import os
from pathlib import Path
import subprocess
import sys
import tempfile
from threading import BoundedSemaphore
import time
from typing import Callable, Literal

from .calculation_artifacts import ArtifactIntegrityError, verify_gzip_artifact
from .model_codec import COMPACT_RESULT_FORMAT
from .schemas import SolveRequest, SolveResponse


APP_ROOT = Path(__file__).resolve().parents[1]
SOLVE_TIMEOUT_SECONDS = max(1, int(os.getenv("FSE3D_SOLVE_TIMEOUT_SECONDS", "45")))
SOLVE_MAX_CONCURRENT = max(1, int(os.getenv("FSE3D_SOLVE_MAX_CONCURRENT", "2")))
SOLVE_PROCESS_ATTEMPTS = min(
    3,
    max(1, int(os.getenv("FSE3D_SOLVE_PROCESS_ATTEMPTS", "2"))),
)
SOLVE_MAX_RESPONSE_BYTES = max(
    1024 * 1024,
    int(os.getenv("FSE3D_SOLVE_RESPONSE_BYTES", str(64 * 1024 * 1024))),
)
_solve_slots = BoundedSemaphore(SOLVE_MAX_CONCURRENT)
SOLVE_LOCK_DIR = Path(
    os.getenv("FSE3D_SOLVE_LOCK_DIR", str(APP_ROOT / "tmp" / "solver-locks"))
)


def _worker_environment() -> dict[str, str]:
    allowed_names = {
        "PATH",
        "PYTHONHOME",
        "PYTHONPATH",
        "SYSTEMROOT",
        "WINDIR",
        "TEMP",
        "TMP",
        "TMPDIR",
        "LD_LIBRARY_PATH",
        "DYLD_LIBRARY_PATH",
    }
    environment = {
        name: value
        for name, value in os.environ.items()
        if name.upper() in allowed_names or name.startswith("FSE3D_SOLVE_")
    }
    environment["PYTHONUNBUFFERED"] = "1"
    return environment


class SolverBusyError(RuntimeError):
    pass


class SolverTimeoutError(RuntimeError):
    pass


class SolverProcessError(RuntimeError):
    pass


class SolverCancelledError(RuntimeError):
    pass


class SolverInterruptedError(RuntimeError):
    pass


@dataclass(frozen=True)
class ArtifactWorkerResult:
    manifest: dict
    result_path: Path


def solve_structure_isolated(request: SolveRequest) -> SolveResponse:
    if not _solve_slots.acquire(blocking=False):
        raise SolverBusyError("Todos os processos de calculo estao ocupados. Tente novamente em instantes.")
    try:
        with _process_slot() as acquired:
            if not acquired:
                raise SolverBusyError(
                    "Todos os processos de calculo estao ocupados. Tente novamente em instantes."
                )
            last_error: SolverProcessError | None = None
            for _attempt in range(SOLVE_PROCESS_ATTEMPTS):
                try:
                    return _run_worker(request)
                except SolverProcessError as exc:
                    last_error = exc
            if last_error is None:  # pragma: no cover - protegido pelo limite minimo
                raise SolverProcessError("O processo isolado de calculo nao foi iniciado.")
            raise last_error
    finally:
        _solve_slots.release()


@contextmanager
def _process_slot():
    if os.name != "posix":
        yield True
        return

    try:
        import fcntl

        SOLVE_LOCK_DIR.mkdir(parents=True, exist_ok=True)
        SOLVE_LOCK_DIR.chmod(0o700)
    except (ImportError, OSError) as exc:
        raise SolverProcessError("Nao foi possivel preparar o controle global de calculos.") from exc

    handle = None
    try:
        for index in range(SOLVE_MAX_CONCURRENT):
            try:
                candidate = (SOLVE_LOCK_DIR / f"slot-{index}.lock").open("a+b")
            except OSError as exc:
                raise SolverProcessError(
                    "Nao foi possivel abrir o controle global de calculos."
                ) from exc
            try:
                fcntl.flock(candidate.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
            except BlockingIOError:
                candidate.close()
                continue
            except OSError as exc:
                candidate.close()
                raise SolverProcessError(
                    "Nao foi possivel bloquear o controle global de calculos."
                ) from exc
            handle = candidate
            break
        yield handle is not None
    finally:
        if handle is not None:
            try:
                fcntl.flock(handle.fileno(), fcntl.LOCK_UN)
            finally:
                handle.close()


def _run_worker(request: SolveRequest) -> SolveResponse:
    request_bytes = request.model_dump_json().encode("utf-8")
    with tempfile.TemporaryDirectory(prefix="fse3d-solve-") as temporary_dir:
        result_path = Path(temporary_dir) / "result.json"
        command = [sys.executable, "-m", "app.solver_worker", str(result_path)]
        creation_flags = getattr(subprocess, "CREATE_NO_WINDOW", 0) if os.name == "nt" else 0
        try:
            completed = subprocess.run(
                command,
                cwd=APP_ROOT,
                env=_worker_environment(),
                input=request_bytes,
                stdout=subprocess.DEVNULL,
                stderr=subprocess.DEVNULL,
                check=False,
                timeout=SOLVE_TIMEOUT_SECONDS,
                creationflags=creation_flags,
            )
        except subprocess.TimeoutExpired as exc:
            raise SolverTimeoutError(
                f"O calculo excedeu o limite de {SOLVE_TIMEOUT_SECONDS} segundos e foi encerrado."
            ) from exc

        if not result_path.exists():
            raise SolverProcessError(
                "O processo isolado do OpenSees foi encerrado inesperadamente sem produzir resultado."
            )
        if result_path.stat().st_size > SOLVE_MAX_RESPONSE_BYTES:
            raise SolverProcessError("A resposta do calculo excedeu o limite de tamanho permitido.")
        try:
            package = json.loads(result_path.read_text(encoding="utf-8"))
        except (OSError, ValueError) as exc:
            raise SolverProcessError("Resposta invalida do processo isolado de calculo.") from exc

        if package.get("ok") is True:
            return SolveResponse.model_validate(package.get("response"))
        message = str(package.get("message") or "Falha no processo isolado de calculo.")
        if package.get("kind") == "validation":
            raise ValueError(message)
        if completed.returncode != 0:
            raise SolverProcessError(message)
        raise SolverProcessError(message)


def run_solver_artifact(
    request_path: Path,
    result_path: Path,
    manifest_path: Path,
    *,
    memory_mb: int,
    timeout_seconds: int,
    max_request_bytes: int,
    max_response_bytes: int,
    expected_request_sha256: str,
    stop_reason: Callable[[], Literal["cancel", "shutdown"] | None],
    heartbeat: Callable[[dict | None], None],
    poll_interval_seconds: float = 0.5,
) -> ArtifactWorkerResult:
    progress_path = manifest_path.with_name(f"{manifest_path.stem}.progress.json")
    environment = _worker_environment()
    environment.update(
        {
            "FSE3D_SOLVE_MEMORY_MB": str(max(0, memory_mb)),
            "FSE3D_SOLVE_CPU_SECONDS": str(max(0, timeout_seconds)),
            "FSE3D_SOLVE_REQUEST_BYTES": str(max(1024, max_request_bytes)),
            "FSE3D_SOLVE_RESPONSE_BYTES": str(max(1024 * 1024, max_response_bytes)),
            "FSE3D_SOLVE_REQUEST_SHA256": expected_request_sha256,
            "FSE3D_SOLVE_PROGRESS_PATH": str(progress_path),
        }
    )
    result_path.unlink(missing_ok=True)
    manifest_path.unlink(missing_ok=True)
    progress_path.unlink(missing_ok=True)
    command = [
        sys.executable,
        "-m",
        "app.solver_worker",
        str(result_path),
        str(request_path),
        str(manifest_path),
    ]
    creation_flags = getattr(subprocess, "CREATE_NO_WINDOW", 0) if os.name == "nt" else 0
    process = subprocess.Popen(
        command,
        cwd=APP_ROOT,
        env=environment,
        stdin=subprocess.DEVNULL,
        stdout=subprocess.DEVNULL,
        stderr=subprocess.DEVNULL,
        creationflags=creation_flags,
        start_new_session=os.name == "posix",
    )
    started = time.monotonic()
    last_heartbeat = 0.0
    try:
        while process.poll() is None:
            reason = stop_reason()
            if reason is not None:
                _terminate_process(process)
                if reason == "cancel":
                    raise SolverCancelledError("Calculo cancelado pelo usuario.")
                raise SolverInterruptedError("Worker interrompido antes da conclusao do calculo.")
            elapsed = time.monotonic() - started
            if timeout_seconds > 0 and elapsed > timeout_seconds:
                _terminate_process(process)
                raise SolverTimeoutError(
                    f"O calculo excedeu o limite configurado de {timeout_seconds} segundos."
                )
            if elapsed - last_heartbeat >= 5.0:
                heartbeat(_read_solver_progress(progress_path))
                last_heartbeat = elapsed
            time.sleep(max(0.05, poll_interval_seconds))
        heartbeat(_read_solver_progress(progress_path))
    except BaseException:
        if process.poll() is None:
            _terminate_process(process)
        progress_path.unlink(missing_ok=True)
        raise

    progress_path.unlink(missing_ok=True)
    if not manifest_path.exists() or manifest_path.stat().st_size > 128 * 1024:
        raise SolverProcessError("O worker terminou sem manifesto valido.")
    try:
        manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
    except (OSError, ValueError) as exc:
        raise SolverProcessError("Manifesto invalido do processo de calculo.") from exc

    if manifest.get("ok") is True and process.returncode == 0:
        if manifest.get("result_format") != COMPACT_RESULT_FORMAT:
            raise SolverProcessError("O worker retornou um formato de resultado incompativel.")
        if not result_path.exists():
            raise SolverProcessError("O worker informou sucesso sem gravar o resultado.")
        try:
            verify_gzip_artifact(
                result_path,
                expected_sha256=manifest.get("response_sha256"),
                expected_uncompressed_size=manifest.get("response_size_bytes"),
                expected_compressed_size=manifest.get("artifact_size_bytes"),
                max_uncompressed_bytes=max_response_bytes,
            )
        except ArtifactIntegrityError as exc:
            result_path.unlink(missing_ok=True)
            raise SolverProcessError(
                "Falha de integridade no artefato de resultado produzido pelo worker."
            ) from exc
        return ArtifactWorkerResult(manifest=manifest, result_path=result_path)

    message = str(manifest.get("message") or "Falha no processo isolado de calculo.")[:1000]
    if manifest.get("kind") == "validation":
        raise ValueError(message)
    raise SolverProcessError(message)


def _read_solver_progress(progress_path: Path) -> dict | None:
    try:
        if not progress_path.exists() or progress_path.stat().st_size > 16 * 1024:
            return None
        payload = json.loads(progress_path.read_text(encoding="utf-8"))
    except (OSError, ValueError):
        return None
    if not isinstance(payload, dict):
        return None
    allowed = {
        "stage",
        "current",
        "total",
        "percent",
        "combination_id",
        "combination_name",
    }
    return {key: payload.get(key) for key in allowed}


def _terminate_process(process: subprocess.Popen) -> None:
    if process.poll() is not None:
        return
    process.terminate()
    try:
        process.wait(timeout=5)
    except subprocess.TimeoutExpired:
        process.kill()
        process.wait(timeout=5)
