use std::path::PathBuf;
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;

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

impl TftpService {
    #[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 tftp_default = format!(
            r#"TFTP_USERNAME="tftp"
TFTP_DIRECTORY="{}"
TFTP_ADDRESS="{}:{}"
TFTP_OPTIONS="{}"
"#,
            self.settings.tftp.root_dir,
            self.settings.tftp.server_ip,
            self.settings.tftp.port,
            self.settings.tftp.options
        );

        write_with_sudo_tee("/etc/default/tftpd-hpa", &tftp_default).await?;

        info!("TFTP configuration written to /etc/default/tftpd-hpa");
        Ok(())
    }

    pub async fn start(&self) -> anyhow::Result<()> {
        // Generate config first
        self.generate_config().await?;

        // Then start tftpd-hpa
        run_sudo_command(["systemctl", "start", "tftpd-hpa"]).await?;

        info!("TFTP service started");
        Ok(())
    }

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

    pub async fn reload(&self) -> anyhow::Result<()> {
        run_sudo_command(["systemctl", "restart", "tftpd-hpa"]).await?;
        info!("TFTP service reloaded");
        Ok(())
    }

    pub async fn get_config(&self) -> anyhow::Result<String> {
        let config_path = PathBuf::from("/etc/default/tftpd-hpa");
        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 tftp_default = format!(
                r#"# Generated by diskless-boot-server
TFTP_USERNAME="tftp"
TFTP_DIRECTORY="{}"
TFTP_ADDRESS="{}:{}"
TFTP_OPTIONS="{}"
"#,
                self.settings.tftp.root_dir,
                self.settings.tftp.server_ip,
                self.settings.tftp.port,
                self.settings.tftp.options
            );
            Ok(tftp_default)
        }
    }

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