use std::sync::Arc;

use crate::core::config::Settings;
use crate::services::{
    get_service_pid, is_systemd_service_running, run_sudo_command, write_with_sudo_tee,
    ServiceStatus,
};
use log::info;

use std::path::PathBuf;

pub struct NfsService {
    pub(crate) settings: Arc<Settings>,
}

impl NfsService {
    #[expect(dead_code, reason = "Constructed directly by ServiceManager::new, not by external callers")]
    pub fn new(settings: Settings) -> Self {
        Self { settings: Arc::new(settings) }
    }

    pub async fn generate_config(&self) -> anyhow::Result<()> {
        let exports_content = format!(
            "# Generated by diskless-boot-server\n\
            {} *(ro,sync,no_subtree_check,no_root_squash)\n",
            self.settings.nfs.exports_dir.display()
        );

        write_with_sudo_tee("/etc/exports", &exports_content).await?;

        info!("NFS exports written to /etc/exports");
        Ok(())
    }

    #[expect(dead_code, reason = "Method kept for future NFS export management")]
    pub async fn add_export(&self, path: &str, options: &str) -> anyhow::Result<()> {
        // Read the existing exports file
        let content = std::fs::read_to_string("/etc/exports").unwrap_or_default();
        let new_content = format!("{}{} {}\n", content, path, options);

        // Use sudo tee to write to system configuration file
        write_with_sudo_tee("/etc/exports", &new_content).await?;

        // Re-export
        run_sudo_command(["exportfs", "-ra"]).await?;

        info!("NFS export added: {}", path);
        Ok(())
    }

    pub async fn start(&self) -> anyhow::Result<()> {
        run_sudo_command(["systemctl", "start", "nfs-kernel-server"]).await?;
        info!("NFS service started");
        Ok(())
    }

    pub async fn stop(&self) -> anyhow::Result<()> {
        run_sudo_command(["systemctl", "stop", "nfs-kernel-server"]).await?;
        info!("NFS service stopped");
        Ok(())
    }

    pub async fn reload(&self) -> anyhow::Result<()> {
        run_sudo_command(["exportfs", "-ra"]).await?;
        info!("NFS exports reloaded");
        Ok(())
    }

    pub async fn get_config(&self) -> anyhow::Result<String> {
        let config_path = PathBuf::from("/etc/exports");
        if config_path.exists() {
            let content = std::fs::read_to_string(&config_path)?;
            Ok(content)
        } else {
            // Return default configuration if file doesn't exist
            let exports_content = format!(
                "# Generated by diskless-boot-server\n\
                {} *(ro,sync,no_subtree_check,no_root_squash)\n",
                self.settings.nfs.exports_dir.display()
            );
            Ok(exports_content)
        }
    }

    pub async fn status(&self) -> anyhow::Result<ServiceStatus> {
        let running = is_systemd_service_running("nfs-kernel-server").await?;
        let pid = get_service_pid("nfs-kernel-server").await?;
        Ok(ServiceStatus {
            running,
            pid,
            message: if running {
                "NFS server is running".to_string()
            } else {
                "NFS server is not running".to_string()
            },
        })
    }
}
