mod transfer;

pub(crate) use transfer::{
    delete_managed_artifact, download_managed_artifact, validate_managed_artifact,
};

use serde::{Deserialize, Serialize};
use std::fmt;
use std::fs;
use std::path::{Path, PathBuf};

pub(crate) const MODEL_CHOICES: [ModelChoice; 4] = [
    ModelChoice::DeepSeekV4Flash,
    ModelChoice::DeepSeekV4Flash0731,
    ModelChoice::DeepSeekV4Pro,
    ModelChoice::Glm52,
];
pub(crate) const MANAGED_ARTIFACTS: [ManagedArtifactId; 6] = [
    ManagedArtifactId::DeepSeekV4Flash,
    ManagedArtifactId::DeepSeekV4FlashMtp,
    ManagedArtifactId::DeepSeekV4FlashDspark,
    ManagedArtifactId::DeepSeekV4Flash0731,
    ManagedArtifactId::DeepSeekV4Pro,
    ManagedArtifactId::Glm52,
];

const DEEPSEEK_REPOSITORY: &str = "antirez/deepseek-v4-gguf";
const DEEPSEEK_FLASH_0731_REPOSITORY: &str = "Rednalreden/DeepSeek-V4-Flash-0731-dwarfstar-q2-gguf";
const GLM_REPOSITORY: &str = "antirez/glm-5.2-gguf";

const FLASH: Artifact = Artifact {
    label: "DeepSeek V4 Flash model",
    file_name: "DeepSeek-V4-Flash-IQ2XXS-w2Q2K-AProjQ8-SExpQ8-OutQ8-chat-v2-imatrix.gguf",
    repository: DEEPSEEK_REPOSITORY,
    size: 86_720_111_488,
    sha256: "efc7ed607ff27076e3e501fc3fefefa33c0ed8cf1eff483a2b7fdc0c2e616668",
    support: Some(false),
};
const FLASH_DSPARK: Artifact = Artifact {
    label: "DSpark support",
    file_name: "DeepSeek-V4-Flash-DSpark-support.gguf",
    repository: DEEPSEEK_REPOSITORY,
    size: 5_989_114_272,
    sha256: "8b3adf5942bec22ae2ea867cd7079cf13530ba83ffcffaf00f5de48664a1a34e",
    support: Some(true),
};
const FLASH_MTP: Artifact = Artifact {
    label: "Legacy MTP support",
    file_name: "DeepSeek-V4-Flash-MTP-Q4K-Q8_0-F32.gguf",
    repository: DEEPSEEK_REPOSITORY,
    size: 3_807_602_400,
    sha256: "afd481ee689dce9037f70f39085fcdae5a5b096d521cdad43b19fa52bf8f4083",
    support: Some(true),
};
const FLASH_0731: Artifact = Artifact {
    label: "DeepSeek V4 Flash 0731 model",
    file_name: "DeepSeek-V4-Flash-0731-IQ2XXS-w2Q2K-AProjQ8-SExpQ8-OutQ8-imatrix.gguf",
    repository: DEEPSEEK_FLASH_0731_REPOSITORY,
    size: 86_720_111_520,
    sha256: "0b39f9c337d6b49c77db2190556b8563abf3c5fbb98be3b58cf8d3a1db191e5f",
    support: Some(false),
};
const PRO: Artifact = Artifact {
    label: "DeepSeek V4 Pro model",
    file_name: "DeepSeek-V4-Pro-IQ2XXS-w2Q2K-AProjQ8-SExpQ8-OutQ8-Instruct-imatrix.gguf",
    repository: DEEPSEEK_REPOSITORY,
    size: 464_627_334_560,
    sha256: "a0314d9c0e16122cd60071079124a2d17185d317c55a8f95ecb3ed3506278a96",
    support: Some(false),
};
const GLM: Artifact = Artifact {
    label: "GLM 5.2 model",
    file_name: "GLM-5.2-UD-IQ2_XXS_RoutedIQ2XXS_blk78Q2K.gguf",
    repository: GLM_REPOSITORY,
    size: 211_075_856_448,
    sha256: "a49de64c5020432bdae23de36a423a9660a5621bc0db8d12b66bd8814b07fea0",
    support: Some(false),
};

#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, Ord, PartialEq, PartialOrd, Serialize)]
pub(crate) enum ModelChoice {
    #[default]
    #[serde(rename = "deepseek-v4-flash")]
    DeepSeekV4Flash,
    #[serde(rename = "deepseek-v4-flash-0731")]
    DeepSeekV4Flash0731,
    #[serde(rename = "deepseek-v4-pro")]
    DeepSeekV4Pro,
    #[serde(rename = "glm-5.2")]
    Glm52,
}

impl ModelChoice {
    pub(crate) fn id(self) -> &'static str {
        match self {
            Self::DeepSeekV4Flash => "deepseek-v4-flash",
            Self::DeepSeekV4Flash0731 => "deepseek-v4-flash-0731",
            Self::DeepSeekV4Pro => "deepseek-v4-pro",
            Self::Glm52 => "glm-5.2",
        }
    }

    pub(crate) fn from_id(id: &str) -> Option<Self> {
        MODEL_CHOICES.into_iter().find(|model| model.id() == id)
    }

    pub(crate) fn supports_dspark(self) -> bool {
        self == Self::DeepSeekV4Flash
    }

    fn main_artifact(self) -> &'static Artifact {
        match self {
            Self::DeepSeekV4Flash => &FLASH,
            Self::DeepSeekV4Flash0731 => &FLASH_0731,
            Self::DeepSeekV4Pro => &PRO,
            Self::Glm52 => &GLM,
        }
    }

    #[cfg(test)]
    fn artifacts(
        self,
        legacy_mtp_enabled: bool,
        dspark_enabled: bool,
    ) -> impl Iterator<Item = &'static Artifact> {
        [
            Some(self.main_artifact()),
            (self.supports_dspark() && legacy_mtp_enabled).then_some(&FLASH_MTP),
            (self.supports_dspark() && dspark_enabled).then_some(&FLASH_DSPARK),
        ]
        .into_iter()
        .flatten()
    }
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub(crate) struct EngineArtifacts {
    pub(crate) model: PathBuf,
    pub(crate) mtp: Option<PathBuf>,
}

pub(crate) fn engine_artifacts(
    model: ModelChoice,
    legacy_mtp_enabled: bool,
    dspark_enabled: bool,
    models_path: &Path,
) -> EngineArtifacts {
    EngineArtifacts {
        model: model.main_artifact().path(model, models_path),
        mtp: if model.supports_dspark() && legacy_mtp_enabled {
            Some(FLASH_MTP.path(model, models_path))
        } else if model.supports_dspark() && dspark_enabled {
            Some(FLASH_DSPARK.path(model, models_path))
        } else {
            None
        },
    }
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum ManagedArtifactId {
    DeepSeekV4Flash,
    DeepSeekV4FlashMtp,
    DeepSeekV4FlashDspark,
    DeepSeekV4Flash0731,
    DeepSeekV4Pro,
    Glm52,
}

impl ManagedArtifactId {
    pub(crate) fn model(self) -> ModelChoice {
        match self {
            Self::DeepSeekV4Flash | Self::DeepSeekV4FlashMtp | Self::DeepSeekV4FlashDspark => {
                ModelChoice::DeepSeekV4Flash
            }
            Self::DeepSeekV4Flash0731 => ModelChoice::DeepSeekV4Flash0731,
            Self::DeepSeekV4Pro => ModelChoice::DeepSeekV4Pro,
            Self::Glm52 => ModelChoice::Glm52,
        }
    }

    fn artifact(self) -> &'static Artifact {
        match self {
            Self::DeepSeekV4Flash => &FLASH,
            Self::DeepSeekV4FlashMtp => &FLASH_MTP,
            Self::DeepSeekV4FlashDspark => &FLASH_DSPARK,
            Self::DeepSeekV4Flash0731 => &FLASH_0731,
            Self::DeepSeekV4Pro => &PRO,
            Self::Glm52 => &GLM,
        }
    }
}

impl fmt::Display for ManagedArtifactId {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(self.artifact().label)
    }
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum ManagedArtifactState {
    Missing,
    Partial,
    NeedsVerification,
    Ready,
}

#[derive(Clone, Debug)]
pub(crate) struct ManagedArtifact {
    pub(crate) id: ManagedArtifactId,
    pub(crate) stored: u64,
    pub(crate) expected: u64,
    pub(crate) state: ManagedArtifactState,
}

impl ManagedArtifact {
    pub(crate) fn can_validate(&self) -> bool {
        matches!(
            self.state,
            ManagedArtifactState::NeedsVerification | ManagedArtifactState::Ready
        )
    }
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum DownloadPhase {
    Pending(&'static str),
    Downloading(&'static str),
    Verifying(&'static str),
    Complete,
}

#[derive(Clone, Debug)]
pub(crate) struct DownloadProgress {
    pub(crate) downloaded: u64,
    pub(crate) total: u64,
    pub(crate) phase: DownloadPhase,
    pub(crate) verification: Option<VerificationProgress>,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) struct VerificationProgress {
    pub(crate) verified: u64,
    pub(crate) total: u64,
}

impl DownloadProgress {
    pub(crate) fn remaining(&self) -> u64 {
        self.active_total().saturating_sub(self.completed())
    }

    pub(crate) fn fraction(&self) -> f32 {
        let total = self.active_total();
        if total == 0 {
            0.0
        } else {
            self.completed() as f32 / total as f32
        }
    }

    pub(crate) fn completed(&self) -> u64 {
        self.verification
            .map_or(self.downloaded, |progress| progress.verified)
    }

    pub(crate) fn active_total(&self) -> u64 {
        self.verification
            .map_or(self.total, |progress| progress.total)
    }
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum DownloadOutcome {
    Complete,
    Stopped,
}

impl fmt::Display for ModelChoice {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(match self {
            Self::DeepSeekV4Flash => "DeepSeek V4 Flash",
            Self::DeepSeekV4Flash0731 => "DeepSeek V4 Flash 0731",
            Self::DeepSeekV4Pro => "DeepSeek V4 Pro",
            Self::Glm52 => "GLM 5.2",
        })
    }
}

struct Artifact {
    label: &'static str,
    file_name: &'static str,
    repository: &'static str,
    size: u64,
    sha256: &'static str,
    support: Option<bool>,
}

impl Artifact {
    fn path(&self, model: ModelChoice, models_path: &Path) -> PathBuf {
        models_path.join(model.id()).join(self.file_name)
    }

    fn url(&self) -> String {
        format!(
            "https://huggingface.co/{}/resolve/main/{}",
            self.repository, self.file_name
        )
    }

    fn verification_path(&self, model: ModelChoice, models_path: &Path) -> PathBuf {
        self.path(model, models_path).with_extension("gguf.sha256")
    }

    fn partial_path(&self, model: ModelChoice, models_path: &Path) -> PathBuf {
        self.path(model, models_path).with_extension("gguf.part")
    }

    fn is_installed(&self, model: ModelChoice, models_path: &Path) -> bool {
        self.path(model, models_path)
            .metadata()
            .is_ok_and(|metadata| metadata.len() == self.size)
            && fs::read_to_string(self.verification_path(model, models_path))
                .is_ok_and(|sha256| sha256.trim() == self.sha256)
    }

    fn downloaded_bytes(&self, model: ModelChoice, models_path: &Path) -> u64 {
        if self.is_installed(model, models_path) {
            return self.size;
        }
        self.path(model, models_path)
            .metadata()
            .or_else(|_| self.partial_path(model, models_path).metadata())
            .map_or(0, |metadata| metadata.len().min(self.size))
    }

    fn stored_bytes(&self, model: ModelChoice, models_path: &Path) -> u64 {
        [
            &self.path(model, models_path),
            &self.partial_path(model, models_path),
        ]
        .into_iter()
        .filter_map(|path| path.metadata().ok())
        .map(|metadata| metadata.len())
        .sum()
    }
}

pub(crate) fn managed_artifacts(models_path: &Path) -> Vec<ManagedArtifact> {
    MANAGED_ARTIFACTS
        .into_iter()
        .map(|id| {
            let model = id.model();
            let artifact = id.artifact();
            let stored = artifact.stored_bytes(model, models_path);
            let complete_file = artifact
                .path(model, models_path)
                .metadata()
                .or_else(|_| artifact.partial_path(model, models_path).metadata())
                .is_ok_and(|metadata| metadata.len() == artifact.size);
            let state = if artifact.is_installed(model, models_path) {
                ManagedArtifactState::Ready
            } else if complete_file {
                ManagedArtifactState::NeedsVerification
            } else if stored > 0 {
                ManagedArtifactState::Partial
            } else {
                ManagedArtifactState::Missing
            };
            ManagedArtifact {
                id,
                stored,
                expected: artifact.size,
                state,
            }
        })
        .collect()
}

pub(crate) fn installed_models(models_path: &Path) -> Vec<ModelChoice> {
    MODEL_CHOICES
        .into_iter()
        .filter(|model| model.main_artifact().is_installed(*model, models_path))
        .collect()
}

pub(crate) fn artifact_download_progress(
    id: ManagedArtifactId,
    models_path: &Path,
) -> DownloadProgress {
    let model = id.model();
    let artifact = id.artifact();
    let downloaded = artifact.downloaded_bytes(model, models_path);
    let installed = artifact.is_installed(model, models_path);
    let verification =
        (!installed && downloaded >= artifact.size).then_some(VerificationProgress {
            verified: 0,
            total: artifact.size,
        });
    let phase = if installed {
        DownloadPhase::Complete
    } else if verification.is_some() {
        DownloadPhase::Verifying(artifact.label)
    } else if downloaded > 0 {
        DownloadPhase::Downloading(artifact.label)
    } else {
        DownloadPhase::Pending(artifact.label)
    };
    DownloadProgress {
        downloaded,
        total: artifact.size,
        phase,
        verification,
    }
}

pub(crate) fn artifact_verification_progress(
    id: ManagedArtifactId,
    verified: u64,
) -> DownloadProgress {
    let artifact = id.artifact();
    DownloadProgress {
        downloaded: artifact.size,
        total: artifact.size,
        phase: DownloadPhase::Verifying(artifact.label),
        verification: Some(VerificationProgress {
            verified: verified.min(artifact.size),
            total: artifact.size,
        }),
    }
}
