from __future__ import annotations

from dataclasses import dataclass
from datetime import timedelta
import logging
import os
from pathlib import Path
import socket
from threading import Event, Thread
from typing import Literal, cast
import uuid

from sqlalchemy import func, select, update
from sqlalchemy.orm import Session

from .calculation_artifacts import CalculationArtifactStore, artifact_store
from .calculation_resources import (
    CALCULATION_CLASSES,
    CLASS_MEMORY_MB,
    CalculationRequirements,
    classes_runnable_by,
    pool_can_run,
)
from .database import SessionLocal
from .isolated_solver import (
    SolverCancelledError,
    SolverInterruptedError,
    SolverProcessError,
    SolverTimeoutError,
    run_solver_artifact,
)
from .models import CalculationJob, CalculationWorker
from .schemas import CalculationClass
from .time_utils import utc_now_naive


LOGGER = logging.getLogger(__name__)
LEASE_SECONDS = max(30, int(os.getenv("FSE3D_JOB_LEASE_SECONDS", "45")))
WORKER_FRESH_SECONDS = max(15, int(os.getenv("FSE3D_JOB_WORKER_FRESH_SECONDS", "30")))
IDLE_POLL_SECONDS = max(0.2, float(os.getenv("FSE3D_JOB_POLL_SECONDS", "1")))

DEFAULT_REQUEST_MB = {
    "small": 32,
    "professional": 64,
    "large": 256,
    "extreme": 512,
}
DEFAULT_RESPONSE_MB = {
    "small": 64,
    "professional": 256,
    "large": 512,
    "extreme": 1024,
}


@dataclass(frozen=True)
class PoolConfig:
    pool_class: CalculationClass
    slots: int
    memory_mb: int
    timeout_seconds: int
    max_request_bytes: int
    max_response_bytes: int


@dataclass(frozen=True)
class ClaimedJob:
    database_id: int
    job_uid: str
    request_artifact: str
    run_token: str
    attempt_count: int
    max_attempts: int


def pool_config(
    pool_class: CalculationClass,
    *,
    slots: int | None = None,
    memory_mb: int | None = None,
    timeout_seconds: int | None = None,
    max_request_mb: int | None = None,
    max_response_mb: int | None = None,
) -> PoolConfig:
    prefix = f"FSE3D_JOB_POOL_{pool_class.upper()}"
    resolved_slots = slots if slots is not None else _env_nonnegative_int(f"{prefix}_WORKERS", 0)
    resolved_memory = memory_mb if memory_mb is not None else _env_nonnegative_int(
        f"{prefix}_MEMORY_MB",
        CLASS_MEMORY_MB[pool_class],
    )
    resolved_timeout = timeout_seconds if timeout_seconds is not None else _env_nonnegative_int(
        f"{prefix}_TIMEOUT_SECONDS",
        0,
    )
    request_mb = max_request_mb if max_request_mb is not None else _env_nonnegative_int(
        f"{prefix}_MAX_REQUEST_MB",
        DEFAULT_REQUEST_MB[pool_class],
    )
    response_mb = max_response_mb if max_response_mb is not None else _env_nonnegative_int(
        f"{prefix}_MAX_RESPONSE_MB",
        DEFAULT_RESPONSE_MB[pool_class],
    )
    return PoolConfig(
        pool_class=pool_class,
        slots=max(0, resolved_slots),
        memory_mb=max(0, resolved_memory),
        timeout_seconds=max(0, resolved_timeout),
        max_request_bytes=max(1, request_mb) * 1024 * 1024,
        max_response_bytes=max(1, response_mb) * 1024 * 1024,
    )


def embedded_pool_configs() -> list[PoolConfig]:
    if not _env_bool("FSE3D_JOB_EMBEDDED_WORKERS", False):
        return []
    configs = [pool_config(cast(CalculationClass, name)) for name in CALCULATION_CLASSES]
    if not any(config.slots for config in configs):
        configs[0] = pool_config("small", slots=1)
    return [config for config in configs if config.slots > 0]


def enqueue_calculation(
    db: Session,
    *,
    user_id: int | None,
    owner_token_hash: str | None,
    job_uid: str,
    requirements: CalculationRequirements,
    request_artifact: str,
    request_sha256: str,
    request_size_bytes: int,
    idempotency_key_hash: str | None,
) -> CalculationJob:
    job = CalculationJob(
        job_uid=job_uid,
        user_id=user_id,
        owner_token_hash=owner_token_hash,
        status="queued",
        required_class=requirements.required_class,
        priority=0,
        node_count=requirements.node_count,
        element_count=requirements.element_count,
        estimated_dof=requirements.estimated_dof,
        estimated_memory_mb=requirements.estimated_memory_mb,
        request_artifact=request_artifact,
        request_sha256=request_sha256,
        request_size_bytes=request_size_bytes,
        idempotency_key_hash=idempotency_key_hash,
    )
    db.add(job)
    db.commit()
    db.refresh(job)
    return job


def capacity_available(db: Session, required_class: CalculationClass) -> bool:
    return any(
        pool_can_run(cast(CalculationClass, worker.pool_class), required_class)
        for worker in _fresh_workers(db)
    )


def capacity_snapshot(db: Session) -> list[dict]:
    workers = _fresh_workers(db)
    snapshots = []
    for pool_class in CALCULATION_CLASSES:
        matching = [worker for worker in workers if worker.pool_class == pool_class]
        snapshots.append(
            {
                "pool_class": pool_class,
                "active_workers": len(matching),
                "busy_workers": sum(bool(worker.active_job_uid) for worker in matching),
                "can_run_classes": list(classes_runnable_by(pool_class)),
            }
        )
    return snapshots


def recover_stale_jobs() -> int:
    now = utc_now_naive()
    recovered = 0
    with SessionLocal() as db:
        stale = list(
            db.execute(
                select(CalculationJob).where(
                    CalculationJob.status.in_(("running", "cancel_requested")),
                    CalculationJob.lease_expires_at.is_not(None),
                    CalculationJob.lease_expires_at < now,
                )
            ).scalars()
        )
        for job in stale:
            previous_token = job.run_token
            if job.status == "cancel_requested":
                values = {
                    "status": "cancelled",
                    "completed_at": now,
                    "error_code": None,
                    "error_message": None,
                }
            elif job.attempt_count < job.max_attempts:
                values = {
                    "status": "queued",
                    "error_code": "worker_lost_retry",
                    "error_message": "Worker perdido; trabalho devolvido a fila.",
                }
            else:
                values = {
                    "status": "failed",
                    "completed_at": now,
                    "error_code": "worker_lost",
                    "error_message": "O worker foi perdido antes da conclusao do calculo.",
                }
            values.update(
                {
                    "worker_uid": None,
                    "run_token": None,
                    "assigned_class": None,
                    "heartbeat_at": None,
                    "lease_expires_at": None,
                }
            )
            result = db.execute(
                update(CalculationJob)
                .where(
                    CalculationJob.id == job.id,
                    CalculationJob.run_token == previous_token,
                    CalculationJob.status == job.status,
                )
                .values(**values)
            )
            recovered += int(result.rowcount or 0)
        db.commit()
    return recovered


class CalculationWorkerPool:
    def __init__(
        self,
        config: PoolConfig,
        *,
        store: CalculationArtifactStore | None = None,
    ) -> None:
        self.config = config
        self.store = store or artifact_store
        self._stop_event = Event()
        self._threads: list[Thread] = []

    def start(self) -> None:
        if self._threads or self.config.slots <= 0:
            return
        if self._stop_event.is_set():
            self._stop_event = Event()
        self.store.initialize()
        recover_stale_jobs()
        for slot in range(self.config.slots):
            thread = Thread(
                target=self._worker_loop,
                name=f"fse3d-{self.config.pool_class}-{slot + 1}",
                daemon=True,
            )
            thread.start()
            self._threads.append(thread)

    def stop(self) -> None:
        self._stop_event.set()

    def join(self, timeout: float | None = None) -> None:
        for thread in self._threads:
            thread.join(timeout=timeout)
        self._threads.clear()

    def _worker_loop(self) -> None:
        worker_uid = str(uuid.uuid4())
        self._register_worker(worker_uid)
        last_recovery = 0.0
        try:
            while not self._stop_event.is_set():
                try:
                    now_monotonic = _monotonic()
                    if now_monotonic - last_recovery >= LEASE_SECONDS:
                        recover_stale_jobs()
                        last_recovery = now_monotonic
                    claimed = self._claim_job(worker_uid)
                    if claimed is None:
                        self._heartbeat_worker(worker_uid, None)
                        self._stop_event.wait(IDLE_POLL_SECONDS)
                        continue
                    self._heartbeat_worker(worker_uid, claimed.job_uid)
                    self._execute_job(worker_uid, claimed)
                    self._heartbeat_worker(worker_uid, None)
                except Exception:
                    LOGGER.exception("Falha transitoria no ciclo do worker %s", worker_uid)
                    self._stop_event.wait(IDLE_POLL_SECONDS)
        finally:
            self._retire_worker(worker_uid)

    def _claim_job(self, worker_uid: str) -> ClaimedJob | None:
        eligible = list(reversed(classes_runnable_by(self.config.pool_class)))
        for required_class in eligible:
            with SessionLocal() as db:
                candidate_ids = list(
                    db.execute(
                        select(CalculationJob.id)
                        .where(
                            CalculationJob.status == "queued",
                            CalculationJob.required_class == required_class,
                        )
                        .order_by(CalculationJob.priority.desc(), CalculationJob.created_at.asc())
                        .limit(20)
                    ).scalars()
                )
                for candidate_id in candidate_ids:
                    now = utc_now_naive()
                    run_token = str(uuid.uuid4())
                    result = db.execute(
                        update(CalculationJob)
                        .where(
                            CalculationJob.id == candidate_id,
                            CalculationJob.status == "queued",
                        )
                        .values(
                            status="running",
                            assigned_class=self.config.pool_class,
                            worker_uid=worker_uid,
                            run_token=run_token,
                            attempt_count=CalculationJob.attempt_count + 1,
                            started_at=func.coalesce(CalculationJob.started_at, now),
                            heartbeat_at=now,
                            lease_expires_at=now + timedelta(seconds=LEASE_SECONDS),
                            error_code=None,
                            error_message=None,
                            result_summary_json=None,
                        )
                    )
                    if not result.rowcount:
                        db.rollback()
                        continue
                    db.commit()
                    job = db.get(CalculationJob, candidate_id)
                    if job is None:
                        return None
                    return ClaimedJob(
                        database_id=job.id,
                        job_uid=job.job_uid,
                        request_artifact=job.request_artifact,
                        run_token=run_token,
                        attempt_count=job.attempt_count,
                        max_attempts=job.max_attempts,
                    )
        return None

    def _execute_job(self, worker_uid: str, job: ClaimedJob) -> None:
        result_path, manifest_path = self.store.prepare_attempt(job.job_uid, job.run_token)
        request_path = self.store.resolve_artifact(job.request_artifact)

        def stop_reason() -> Literal["cancel", "shutdown"] | None:
            try:
                with SessionLocal() as db:
                    state = db.execute(
                        select(CalculationJob.status, CalculationJob.run_token).where(
                            CalculationJob.id == job.database_id
                        )
                    ).one_or_none()
                if state is None or state.run_token != job.run_token:
                    return "shutdown"
                if state.status == "cancel_requested":
                    return "cancel"
                if state.status != "running":
                    return "shutdown"
            except Exception:
                LOGGER.exception("Nao foi possivel consultar cancelamento do trabalho %s", job.job_uid)
            if self._stop_event.is_set():
                return "shutdown"
            return None

        def heartbeat(progress: dict | None = None) -> None:
            now = utc_now_naive()
            try:
                with SessionLocal() as db:
                    db.execute(
                        update(CalculationJob)
                        .where(
                            CalculationJob.id == job.database_id,
                            CalculationJob.run_token == job.run_token,
                            CalculationJob.status.in_(("running", "cancel_requested")),
                        )
                        .values(
                            heartbeat_at=now,
                            lease_expires_at=now + timedelta(seconds=LEASE_SECONDS),
                            **(
                                {"result_summary_json": {"kind": "progress", **progress}}
                                if progress
                                else {}
                            ),
                        )
                    )
                    db.execute(
                        update(CalculationWorker)
                        .where(CalculationWorker.worker_uid == worker_uid)
                        .values(heartbeat_at=now, active_job_uid=job.job_uid, status="active")
                    )
                    db.commit()
            except Exception:
                LOGGER.exception("Falha ao renovar o lease do trabalho %s", job.job_uid)

        try:
            worker_result = run_solver_artifact(
                request_path,
                result_path,
                manifest_path,
                memory_mb=self.config.memory_mb,
                timeout_seconds=self.config.timeout_seconds,
                max_request_bytes=self.config.max_request_bytes,
                max_response_bytes=self.config.max_response_bytes,
                stop_reason=stop_reason,
                heartbeat=heartbeat,
            )
            self._finish_success(job, worker_result.manifest, worker_result.result_path)
        except SolverCancelledError:
            self._finish_cancelled(job)
        except SolverInterruptedError:
            self._return_to_queue(job, "worker_stopped", "Worker interrompido; trabalho devolvido a fila.")
        except SolverTimeoutError as exc:
            self._finish_failed(job, "timeout", str(exc))
        except ValueError as exc:
            self._finish_failed(job, "calculation", str(exc))
        except SolverProcessError as exc:
            self._retry_or_fail(job, "worker", str(exc))
        except Exception:
            LOGGER.exception("Falha inesperada no trabalho %s", job.job_uid)
            self._retry_or_fail(job, "worker_internal", "Falha interna no worker de calculo.")
        finally:
            manifest_path.unlink(missing_ok=True)
            if not self._job_owns_result(job, result_path):
                result_path.unlink(missing_ok=True)

    def _finish_success(self, job: ClaimedJob, manifest: dict, result_path: Path) -> None:
        now = utc_now_naive()
        relative_result = self.store.relative_path(result_path)
        with SessionLocal() as db:
            result = db.execute(
                update(CalculationJob)
                .where(
                    CalculationJob.id == job.database_id,
                    CalculationJob.run_token == job.run_token,
                    CalculationJob.status == "running",
                )
                .values(
                    status="succeeded",
                    result_artifact=relative_result,
                    result_sha256=str(manifest.get("response_sha256") or "")[:64],
                    result_size_bytes=int(manifest.get("response_size_bytes") or 0),
                    result_summary_json=manifest.get("summary"),
                    completed_at=now,
                    heartbeat_at=now,
                    lease_expires_at=None,
                    error_code=None,
                    error_message=None,
                )
            )
            db.commit()
        if not result.rowcount:
            result_path.unlink(missing_ok=True)
            self._finish_cancelled(job)

    def _finish_cancelled(self, job: ClaimedJob) -> None:
        self._finish_terminal(job, status="cancelled", error_code=None, error_message=None)

    def _finish_failed(self, job: ClaimedJob, error_code: str, error_message: str) -> None:
        self._finish_terminal(
            job,
            status="failed",
            error_code=error_code,
            error_message=error_message[:1000],
        )

    def _finish_terminal(
        self,
        job: ClaimedJob,
        *,
        status: Literal["failed", "cancelled"],
        error_code: str | None,
        error_message: str | None,
    ) -> None:
        now = utc_now_naive()
        with SessionLocal() as db:
            db.execute(
                update(CalculationJob)
                .where(
                    CalculationJob.id == job.database_id,
                    CalculationJob.run_token == job.run_token,
                    CalculationJob.status.in_(("running", "cancel_requested")),
                )
                .values(
                    status=status,
                    completed_at=now,
                    heartbeat_at=now,
                    lease_expires_at=None,
                    error_code=error_code,
                    error_message=error_message,
                )
            )
            db.commit()

    def _retry_or_fail(self, job: ClaimedJob, error_code: str, error_message: str) -> None:
        if job.attempt_count < job.max_attempts:
            self._return_to_queue(job, f"{error_code}_retry", error_message)
        else:
            self._finish_failed(job, error_code, error_message)

    def _return_to_queue(self, job: ClaimedJob, error_code: str, error_message: str) -> None:
        with SessionLocal() as db:
            db.execute(
                update(CalculationJob)
                .where(
                    CalculationJob.id == job.database_id,
                    CalculationJob.run_token == job.run_token,
                    CalculationJob.status == "running",
                )
                .values(
                    status="queued",
                    assigned_class=None,
                    worker_uid=None,
                    run_token=None,
                    heartbeat_at=None,
                    lease_expires_at=None,
                    error_code=error_code,
                    error_message=error_message[:1000],
                )
            )
            db.commit()

    def _job_owns_result(self, job: ClaimedJob, result_path: Path) -> bool:
        relative = self.store.relative_path(result_path)
        with SessionLocal() as db:
            stored = db.execute(
                select(CalculationJob.result_artifact).where(
                    CalculationJob.id == job.database_id,
                    CalculationJob.status == "succeeded",
                )
            ).scalar_one_or_none()
        return stored == relative

    def _register_worker(self, worker_uid: str) -> None:
        now = utc_now_naive()
        with SessionLocal() as db:
            db.merge(
                CalculationWorker(
                    worker_uid=worker_uid,
                    hostname=socket.gethostname()[:255],
                    process_id=os.getpid(),
                    pool_class=self.config.pool_class,
                    status="active",
                    started_at=now,
                    heartbeat_at=now,
                )
            )
            db.commit()

    def _heartbeat_worker(self, worker_uid: str, active_job_uid: str | None) -> None:
        with SessionLocal() as db:
            db.execute(
                update(CalculationWorker)
                .where(CalculationWorker.worker_uid == worker_uid)
                .values(
                    status="active",
                    active_job_uid=active_job_uid,
                    heartbeat_at=utc_now_naive(),
                )
            )
            db.commit()

    def _retire_worker(self, worker_uid: str) -> None:
        try:
            with SessionLocal() as db:
                db.execute(
                    update(CalculationWorker)
                    .where(CalculationWorker.worker_uid == worker_uid)
                    .values(
                        status="stopped",
                        active_job_uid=None,
                        heartbeat_at=utc_now_naive(),
                    )
                )
                db.commit()
        except Exception:
            LOGGER.exception("Nao foi possivel aposentar o registro do worker")


class CalculationDispatcher:
    def __init__(self, configs: list[PoolConfig] | None = None) -> None:
        self.configs = configs if configs is not None else embedded_pool_configs()
        self.pools = [CalculationWorkerPool(config) for config in self.configs]

    def start(self) -> None:
        for pool in self.pools:
            pool.start()

    def stop(self) -> None:
        for pool in self.pools:
            pool.stop()
        for pool in self.pools:
            pool.join(timeout=10)


def _fresh_workers(db: Session) -> list[CalculationWorker]:
    threshold = utc_now_naive() - timedelta(seconds=WORKER_FRESH_SECONDS)
    return list(
        db.execute(
            select(CalculationWorker).where(
                CalculationWorker.status == "active",
                CalculationWorker.heartbeat_at >= threshold,
            )
        ).scalars()
    )


def _env_nonnegative_int(name: str, default: int) -> int:
    try:
        return max(0, int(os.getenv(name, str(default))))
    except ValueError:
        return default


def _env_bool(name: str, default: bool) -> bool:
    value = os.getenv(name)
    if value is None:
        return default
    return value.strip().lower() in {"1", "true", "yes", "on"}


def _monotonic() -> float:
    import time

    return time.monotonic()
