use dbus::blocking::Connection;
use dbus::channel::MatchingReceiver;
use dbus::message::MatchRule;
use dbus::strings::Member;
use dbus::Path;
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use std::time::{SystemTime, UNIX_EPOCH};
use tracing::{info, warn, error};
use apt_ostree::daemon_client;
use apt_ostree::ostree::OstreeManager;
use apt_ostree::apt_database::{AptDatabaseManager, AptDatabaseConfig};
use apt_ostree::package_manager::{PackageManager, InstallOptions, RemoveOptions};
use apt_ostree::performance::PerformanceManager;
use uuid::Uuid;

/// D-Bus daemon for apt-ostree privileged operations
struct AptOstreeDaemon {
    ostree_manager: Arc<Mutex<OstreeManager>>,
    apt_manager: Arc<Mutex<AptDatabaseManager>>,
    package_manager: Arc<Mutex<PackageManager>>,
    performance_manager: Arc<PerformanceManager>,
    transaction_state: Arc<Mutex<HashMap<String, TransactionState>>>,
    system_status: Arc<Mutex<SystemStatus>>,
}

/// Enhanced transaction state tracking
#[derive(Debug, Clone)]
struct TransactionState {
    id: String,
    operation: String,
    status: TransactionStatus,
    created_at: u64,
    updated_at: u64,
    details: HashMap<String, String>,
    progress: f64,
    error_message: Option<String>,
    rollback_available: bool,
}

#[derive(Debug, Clone)]
enum TransactionStatus {
    Pending,
    InProgress,
    Completed,
    Failed,
    Cancelled,
    RollingBack,
}

/// System status tracking
#[derive(Debug, Clone)]
struct SystemStatus {
    booted_deployment: Option<String>,
    pending_deployment: Option<String>,
    available_upgrades: Vec<String>,
    last_upgrade_check: u64,
    system_health: SystemHealth,
    performance_metrics: Option<String>,
}

#[derive(Debug, Clone)]
enum SystemHealth {
    Healthy,
    Warning,
    Critical,
    Unknown,
}

impl AptOstreeDaemon {
    fn new() -> Result<Self, Box<dyn std::error::Error>> {
        let ostree_manager = Arc::new(Mutex::new(OstreeManager::new("/")?));
        let config = AptDatabaseConfig::default();
        let apt_manager = Arc::new(Mutex::new(AptDatabaseManager::new(config)?));
        let package_manager = Arc::new(Mutex::new(PackageManager::new()?));
        let performance_manager = Arc::new(PerformanceManager::new(10, 512));
        let transaction_state = Arc::new(Mutex::new(HashMap::new()));
        
        let system_status = Arc::new(Mutex::new(SystemStatus {
            booted_deployment: None,
            pending_deployment: None,
            available_upgrades: Vec::new(),
            last_upgrade_check: 0,
            system_health: SystemHealth::Unknown,
            performance_metrics: None,
        }));

        Ok(AptOstreeDaemon {
            ostree_manager,
            apt_manager,
            package_manager,
            performance_manager,
            transaction_state,
            system_status,
        })
    }

    /// Start the D-Bus daemon
    fn run(&self) -> Result<(), Box<dyn std::error::Error>> {
        info!("Starting apt-ostree D-Bus daemon...");

        // Initialize system status
        self.initialize_system_status()?;

        // Create D-Bus connection
        let conn = Connection::new_system()?;
        
        // Request the D-Bus name
        conn.request_name("org.aptostree.dev", false, true, false)?;
        
        info!("D-Bus daemon started successfully on org.aptostree.dev");

        // Set up method handlers
        let daemon = self.clone();
        conn.add_match(
            MatchRule::new_method_call(),
            move |msg, conn| {
                daemon.handle_method_call(msg, conn)
            },
        )?;

        // Main event loop
        loop {
            conn.process(std::time::Duration::from_millis(1000))?;
            
            // Periodic system status updates
            if let Err(e) = self.update_system_status() {
                warn!("Failed to update system status: {}", e);
            }
        }
    }

    /// Initialize system status
    fn initialize_system_status(&self) -> Result<(), Box<dyn std::error::Error>> {
        info!("Initializing system status...");
        
        // Get current deployment info
        let ostree_manager = self.ostree_manager.lock().unwrap();
        if let Ok(deployments) = ostree_manager.list_deployments() {
            if let Some(latest) = deployments.first() {
                let mut status = self.system_status.lock().unwrap();
                status.booted_deployment = Some(latest.commit.clone());
                status.system_health = SystemHealth::Healthy;
            }
        }
        
        Ok(())
    }

    /// Update system status periodically
    fn update_system_status(&self) -> Result<(), Box<dyn std::error::Error>> {
        let now = SystemTime::now().duration_since(UNIX_EPOCH)?.as_secs();
        
        // Update every 5 minutes
        let mut status = self.system_status.lock().unwrap();
        if now - status.last_upgrade_check > 300 {
            status.last_upgrade_check = now;
            
            // Check for available upgrades
            let apt_manager = self.apt_manager.lock().unwrap();
            if let Ok(upgrades) = apt_manager.get_upgradable_packages() {
                status.available_upgrades = upgrades;
            }
            
            // Update performance metrics
            let metrics = self.performance_manager.get_metrics();
            status.performance_metrics = Some(format!("{:?}", metrics));
        }
        
        Ok(())
    }

    /// Handle D-Bus method calls
    fn handle_method_call(&self, msg: dbus::Message, conn: &Connection) -> bool {
        let member = msg.member().unwrap_or_default();
        let path = msg.path().unwrap_or_default();

        info!("Handling D-Bus method call: {} on {}", member, path);

        match member.as_str() {
            "Ping" => self.handle_ping(msg, conn),
            "Status" => self.handle_status(msg, conn),
            "InstallPackages" => self.handle_install_packages(msg, conn),
            "RemovePackages" => self.handle_remove_packages(msg, conn),
            "UpgradeSystem" => self.handle_upgrade_system(msg, conn),
            "Rollback" => self.handle_rollback(msg, conn),
            "ListPackages" => self.handle_list_packages(msg, conn),
            "SearchPackages" => self.handle_search_packages(msg, conn),
            "ShowPackageInfo" => self.handle_show_package_info(msg, conn),
            "Initialize" => self.handle_initialize(msg, conn),
            "CancelTransaction" => self.handle_cancel_transaction(msg, conn),
            "GetTransactionStatus" => self.handle_get_transaction_status(msg, conn),
            "GetSystemStatus" => self.handle_get_system_status(msg, conn),
            "GetPerformanceMetrics" => self.handle_get_performance_metrics(msg, conn),
            "StageDeployment" => self.handle_stage_deployment(msg, conn),
            "CreatePackageLayer" => self.handle_create_package_layer(msg, conn),
            "ExtractCommitMetadata" => self.handle_extract_commit_metadata(msg, conn),
            _ => {
                warn!("Unknown method call: {}", member);
                false
            }
        }
    }

    /// Handle ping method
    fn handle_ping(&self, msg: dbus::Message, conn: &Connection) -> bool {
        info!("Handling ping request");
        
        let response = msg.method_return()
            .append1("pong")
            .append1(SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs());
        
        conn.send_message(&response).is_ok()
    }

    /// Handle status method
    fn handle_status(&self, msg: dbus::Message, conn: &Connection) -> bool {
        info!("Handling status request");
        
        let status = match self.get_system_status() {
            Ok(status) => status,
            Err(e) => {
                error!("Failed to get system status: {}", e);
                return false;
            }
        };
        
        let response = msg.method_return().append1(status);
        conn.send_message(&response).is_ok()
    }

    /// Handle install packages method with enhanced features
    fn handle_install_packages(&self, msg: dbus::Message, conn: &Connection) -> bool {
        let packages: Vec<String> = msg.get1().unwrap_or_default();
        let dry_run: bool = msg.get2().unwrap_or(false);
        let options: Option<InstallOptions> = msg.get3();
        
        info!("Handling install packages request: {:?}, dry_run: {}", packages, dry_run);
        
        let transaction_id = self.create_transaction("install_packages", &packages);
        
        // Update transaction progress
        self.update_transaction_progress(&transaction_id, 0.1);
        
        let result = match self.install_packages(&packages, dry_run, options.as_ref()) {
            Ok(result) => {
                self.update_transaction_progress(&transaction_id, 1.0);
                self.update_transaction_status(&transaction_id, TransactionStatus::Completed);
                result
            }
            Err(e) => {
                self.update_transaction_status(&transaction_id, TransactionStatus::Failed);
                self.update_transaction_error(&transaction_id, &e.to_string());
                format!("Error: {}", e)
            }
        };
        
        let response = msg.method_return()
            .append1(transaction_id)
            .append1(result);
        
        conn.send_message(&response).is_ok()
    }

    /// Handle remove packages method with enhanced features
    fn handle_remove_packages(&self, msg: dbus::Message, conn: &Connection) -> bool {
        let packages: Vec<String> = msg.get1().unwrap_or_default();
        let dry_run: bool = msg.get2().unwrap_or(false);
        let options: Option<RemoveOptions> = msg.get3();
        
        info!("Handling remove packages request: {:?}, dry_run: {}", packages, dry_run);
        
        let transaction_id = self.create_transaction("remove_packages", &packages);
        
        // Update transaction progress
        self.update_transaction_progress(&transaction_id, 0.1);
        
        let result = match self.remove_packages(&packages, dry_run, options.as_ref()) {
            Ok(result) => {
                self.update_transaction_progress(&transaction_id, 1.0);
                self.update_transaction_status(&transaction_id, TransactionStatus::Completed);
                result
            }
            Err(e) => {
                self.update_transaction_status(&transaction_id, TransactionStatus::Failed);
                self.update_transaction_error(&transaction_id, &e.to_string());
                format!("Error: {}", e)
            }
        };
        
        let response = msg.method_return()
            .append1(transaction_id)
            .append1(result);
        
        conn.send_message(&response).is_ok()
    }

    /// Handle upgrade system method with enhanced features
    fn handle_upgrade_system(&self, msg: dbus::Message, conn: &Connection) -> bool {
        let dry_run: bool = msg.get1().unwrap_or(false);
        let allow_downgrade: bool = msg.get2().unwrap_or(false);
        
        info!("Handling upgrade system request, dry_run: {}, allow_downgrade: {}", dry_run, allow_downgrade);
        
        let transaction_id = self.create_transaction("upgrade_system", &[]);
        
        // Update transaction progress
        self.update_transaction_progress(&transaction_id, 0.1);
        
        let result = match self.upgrade_system(dry_run, allow_downgrade) {
            Ok(result) => {
                self.update_transaction_progress(&transaction_id, 1.0);
                self.update_transaction_status(&transaction_id, TransactionStatus::Completed);
                result
            }
            Err(e) => {
                self.update_transaction_status(&transaction_id, TransactionStatus::Failed);
                self.update_transaction_error(&transaction_id, &e.to_string());
                format!("Error: {}", e)
            }
        };
        
        let response = msg.method_return()
            .append1(transaction_id)
            .append1(result);
        
        conn.send_message(&response).is_ok()
    }

    /// Handle rollback method with enhanced features
    fn handle_rollback(&self, msg: dbus::Message, conn: &Connection) -> bool {
        let target_commit: Option<String> = msg.get1();
        
        info!("Handling rollback request, target_commit: {:?}", target_commit);
        
        let transaction_id = self.create_transaction("rollback", &[]);
        
        // Update transaction progress
        self.update_transaction_progress(&transaction_id, 0.1);
        
        let result = match self.rollback_system(target_commit.as_deref()) {
            Ok(result) => {
                self.update_transaction_progress(&transaction_id, 1.0);
                self.update_transaction_status(&transaction_id, TransactionStatus::Completed);
                result
            }
            Err(e) => {
                self.update_transaction_status(&transaction_id, TransactionStatus::Failed);
                self.update_transaction_error(&transaction_id, &e.to_string());
                format!("Error: {}", e)
            }
        };
        
        let response = msg.method_return()
            .append1(transaction_id)
            .append1(result);
        
        conn.send_message(&response).is_ok()
    }

    /// Handle list packages method
    fn handle_list_packages(&self, msg: dbus::Message, conn: &Connection) -> bool {
        let installed_only: bool = msg.get1().unwrap_or(false);
        
        info!("Handling list packages request, installed_only: {}", installed_only);
        
        let result = match self.list_packages(installed_only) {
            Ok(packages) => packages,
            Err(e) => {
                error!("Failed to list packages: {}", e);
                return false;
            }
        };
        
        let response = msg.method_return().append1(result);
        conn.send_message(&response).is_ok()
    }

    /// Handle search packages method
    fn handle_search_packages(&self, msg: dbus::Message, conn: &Connection) -> bool {
        let query: String = msg.get1().unwrap_or_default();
        let search_type: String = msg.get2().unwrap_or_else(|| "name".to_string());
        
        info!("Handling search packages request: '{}', type: {}", query, search_type);
        
        let result = match self.search_packages(&query, &search_type) {
            Ok(packages) => packages,
            Err(e) => {
                error!("Failed to search packages: {}", e);
                return false;
            }
        };
        
        let response = msg.method_return().append1(result);
        conn.send_message(&response).is_ok()
    }

    /// Handle show package info method
    fn handle_show_package_info(&self, msg: dbus::Message, conn: &Connection) -> bool {
        let package: String = msg.get1().unwrap_or_default();
        
        info!("Handling show package info request: {}", package);
        
        let result = match self.show_package_info(&package) {
            Ok(info) => info,
            Err(e) => {
                error!("Failed to show package info: {}", e);
                return false;
            }
        };
        
        let response = msg.method_return().append1(result);
        conn.send_message(&response).is_ok()
    }

    /// Handle initialize method
    fn handle_initialize(&self, msg: dbus::Message, conn: &Connection) -> bool {
        let branch: Option<String> = msg.get1();
        
        info!("Handling initialize request, branch: {:?}", branch);
        
        let transaction_id = self.create_transaction("initialize", &[]);
        
        let result = match self.initialize_system(branch.as_deref()) {
            Ok(result) => {
                self.update_transaction_status(&transaction_id, TransactionStatus::Completed);
                result
            }
            Err(e) => {
                self.update_transaction_status(&transaction_id, TransactionStatus::Failed);
                self.update_transaction_error(&transaction_id, &e.to_string());
                format!("Error: {}", e)
            }
        };
        
        let response = msg.method_return()
            .append1(transaction_id)
            .append1(result);
        
        conn.send_message(&response).is_ok()
    }

    /// Handle cancel transaction method
    fn handle_cancel_transaction(&self, msg: dbus::Message, conn: &Connection) -> bool {
        let transaction_id: String = msg.get1().unwrap_or_default();
        
        info!("Handling cancel transaction request: {}", transaction_id);
        
        let result = match self.cancel_transaction(&transaction_id) {
            Ok(result) => result,
            Err(e) => {
                error!("Failed to cancel transaction: {}", e);
                return false;
            }
        };
        
        let response = msg.method_return().append1(result);
        conn.send_message(&response).is_ok()
    }

    /// Handle get transaction status method
    fn handle_get_transaction_status(&self, msg: dbus::Message, conn: &Connection) -> bool {
        let transaction_id: String = msg.get1().unwrap_or_default();
        
        info!("Handling get transaction status request: {}", transaction_id);
        
        let result = match self.get_transaction_status(&transaction_id) {
            Ok(status) => status,
            Err(e) => {
                error!("Failed to get transaction status: {}", e);
                return false;
            }
        };
        
        let response = msg.method_return().append1(result);
        conn.send_message(&response).is_ok()
    }

    /// Handle get system status method
    fn handle_get_system_status(&self, msg: dbus::Message, conn: &Connection) -> bool {
        info!("Handling get system status request");
        
        let status = self.system_status.lock().unwrap();
        let status_json = serde_json::to_string(&*status).unwrap_or_else(|_| "{}".to_string());
        
        let response = msg.method_return().append1(status_json);
        conn.send_message(&response).is_ok()
    }

    /// Handle get performance metrics method
    fn handle_get_performance_metrics(&self, msg: dbus::Message, conn: &Connection) -> bool {
        info!("Handling get performance metrics request");
        
        let metrics = self.performance_manager.get_metrics();
        let metrics_json = serde_json::to_string(&metrics).unwrap_or_else(|_| "{}".to_string());
        
        let response = msg.method_return().append1(metrics_json);
        conn.send_message(&response).is_ok()
    }

    /// Handle stage deployment method
    fn handle_stage_deployment(&self, msg: dbus::Message, conn: &Connection) -> bool {
        let commit_checksum: String = msg.get1().unwrap_or_default();
        let options_json: String = msg.get2().unwrap_or_default();
        
        info!("Handling stage deployment request: {}", commit_checksum);
        
        let transaction_id = self.create_transaction("stage_deployment", &[commit_checksum.clone()]);
        
        let result = match self.stage_deployment(&commit_checksum, &options_json) {
            Ok(result) => {
                self.update_transaction_status(&transaction_id, TransactionStatus::Completed);
                result
            }
            Err(e) => {
                self.update_transaction_status(&transaction_id, TransactionStatus::Failed);
                self.update_transaction_error(&transaction_id, &e.to_string());
                format!("Error: {}", e)
            }
        };
        
        let response = msg.method_return()
            .append1(transaction_id)
            .append1(result);
        
        conn.send_message(&response).is_ok()
    }

    /// Handle create package layer method
    fn handle_create_package_layer(&self, msg: dbus::Message, conn: &Connection) -> bool {
        let packages: Vec<String> = msg.get1().unwrap_or_default();
        let options_json: String = msg.get2().unwrap_or_default();
        
        info!("Handling create package layer request: {:?}", packages);
        
        let transaction_id = self.create_transaction("create_package_layer", &packages);
        
        let result = match self.create_package_layer(&packages, &options_json) {
            Ok(result) => {
                self.update_transaction_status(&transaction_id, TransactionStatus::Completed);
                result
            }
            Err(e) => {
                self.update_transaction_status(&transaction_id, TransactionStatus::Failed);
                self.update_transaction_error(&transaction_id, &e.to_string());
                format!("Error: {}", e)
            }
        };
        
        let response = msg.method_return()
            .append1(transaction_id)
            .append1(result);
        
        conn.send_message(&response).is_ok()
    }

    /// Handle extract commit metadata method
    fn handle_extract_commit_metadata(&self, msg: dbus::Message, conn: &Connection) -> bool {
        let commit_checksum: String = msg.get1().unwrap_or_default();
        
        info!("Handling extract commit metadata request: {}", commit_checksum);
        
        let result = match self.extract_commit_metadata(&commit_checksum) {
            Ok(metadata) => metadata,
            Err(e) => {
                error!("Failed to extract commit metadata: {}", e);
                return false;
            }
        };
        
        let response = msg.method_return().append1(result);
        conn.send_message(&response).is_ok()
    }

    /// Get system status
    fn get_system_status(&self) -> Result<String, Box<dyn std::error::Error>> {
        let status = self.system_status.lock().unwrap();
        Ok(serde_json::to_string(&*status)?)
    }

    /// Install packages with enhanced features
    fn install_packages(&self, packages: &[String], dry_run: bool, options: Option<&InstallOptions>) -> Result<String, Box<dyn std::error::Error>> {
        let package_manager = self.package_manager.lock().unwrap();
        
        let install_options = options.cloned().unwrap_or_default();
        
        if dry_run {
            let result = package_manager.dry_run_install(packages, &install_options)?;
            Ok(format!("Dry run completed. Would install: {}", result))
        } else {
            let result = package_manager.install_packages(packages, &install_options)?;
            Ok(format!("Installation completed: {}", result))
        }
    }

    /// Remove packages with enhanced features
    fn remove_packages(&self, packages: &[String], dry_run: bool, options: Option<&RemoveOptions>) -> Result<String, Box<dyn std::error::Error>> {
        let package_manager = self.package_manager.lock().unwrap();
        
        let remove_options = options.cloned().unwrap_or_default();
        
        if dry_run {
            let result = package_manager.dry_run_remove(packages, &remove_options)?;
            Ok(format!("Dry run completed. Would remove: {}", result))
        } else {
            let result = package_manager.remove_packages(packages, &remove_options)?;
            Ok(format!("Removal completed: {}", result))
        }
    }

    /// Upgrade system with enhanced features
    fn upgrade_system(&self, dry_run: bool, allow_downgrade: bool) -> Result<String, Box<dyn std::error::Error>> {
        let package_manager = self.package_manager.lock().unwrap();
        
        if dry_run {
            let result = package_manager.dry_run_upgrade(allow_downgrade)?;
            Ok(format!("Dry run upgrade completed. Would upgrade: {}", result))
        } else {
            let result = package_manager.upgrade_system(allow_downgrade)?;
            Ok(format!("Upgrade completed: {}", result))
        }
    }

    /// Rollback system with enhanced features
    fn rollback_system(&self, target_commit: Option<&str>) -> Result<String, Box<dyn std::error::Error>> {
        let ostree_manager = self.ostree_manager.lock().unwrap();
        
        if let Some(commit) = target_commit {
            ostree_manager.rollback("", commit)?;
            Ok(format!("Rolled back to commit: {}", commit))
        } else {
            ostree_manager.rollback_to_previous_deployment()?;
            Ok("Rolled back to previous deployment".to_string())
        }
    }

    /// List packages with enhanced features
    fn list_packages(&self, installed_only: bool) -> Result<Vec<String>, Box<dyn std::error::Error>> {
        let apt_manager = self.apt_manager.lock().unwrap();
        
        if installed_only {
            apt_manager.get_installed_packages()
        } else {
            apt_manager.get_all_packages()
        }
    }

    /// Search packages with enhanced features
    fn search_packages(&self, query: &str, search_type: &str) -> Result<Vec<String>, Box<dyn std::error::Error>> {
        let apt_manager = self.apt_manager.lock().unwrap();
        
        match search_type {
            "name" => apt_manager.search_packages_by_name(query),
            "description" => apt_manager.search_packages_by_description(query),
            "file" => apt_manager.search_packages_by_file(query),
            _ => apt_manager.search_packages_by_name(query),
        }
    }

    /// Show package info with enhanced features
    fn show_package_info(&self, package: &str) -> Result<String, Box<dyn std::error::Error>> {
        let apt_manager = self.apt_manager.lock().unwrap();
        let info = apt_manager.get_package_info(package)?;
        Ok(serde_json::to_string_pretty(&info)?)
    }

    /// Initialize system with enhanced features
    fn initialize_system(&self, branch: Option<&str>) -> Result<String, Box<dyn std::error::Error>> {
        let ostree_manager = self.ostree_manager.lock().unwrap();
        
        if let Some(branch_name) = branch {
            ostree_manager.create_branch(branch_name, None)?;
            Ok(format!("System initialized with branch: {}", branch_name))
        } else {
            ostree_manager.initialize()?;
            Ok("System initialized with default branch".to_string())
        }
    }

    /// Create transaction with enhanced tracking
    fn create_transaction(&self, operation: &str, details: &[String]) -> String {
        let transaction_id = Uuid::new_v4().to_string();
        let now = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs();
        
        let transaction = TransactionState {
            id: transaction_id.clone(),
            operation: operation.to_string(),
            status: TransactionStatus::Pending,
            created_at: now,
            updated_at: now,
            details: details.iter().enumerate().map(|(i, detail)| (i.to_string(), detail.clone())).collect(),
            progress: 0.0,
            error_message: None,
            rollback_available: false,
        };
        
        let mut transactions = self.transaction_state.lock().unwrap();
        transactions.insert(transaction_id.clone(), transaction);
        
        info!("Created transaction: {} for operation: {}", transaction_id, operation);
        transaction_id
    }

    /// Update transaction status
    fn update_transaction_status(&self, transaction_id: &str, status: TransactionStatus) {
        let mut transactions = self.transaction_state.lock().unwrap();
        if let Some(transaction) = transactions.get_mut(transaction_id) {
            transaction.status = status;
            transaction.updated_at = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs();
            info!("Updated transaction {} status to {:?}", transaction_id, status);
        }
    }

    /// Update transaction progress
    fn update_transaction_progress(&self, transaction_id: &str, progress: f64) {
        let mut transactions = self.transaction_state.lock().unwrap();
        if let Some(transaction) = transactions.get_mut(transaction_id) {
            transaction.progress = progress;
            transaction.updated_at = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs();
        }
    }

    /// Update transaction error
    fn update_transaction_error(&self, transaction_id: &str, error: &str) {
        let mut transactions = self.transaction_state.lock().unwrap();
        if let Some(transaction) = transactions.get_mut(transaction_id) {
            transaction.error_message = Some(error.to_string());
            transaction.updated_at = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs();
        }
    }

    /// Cancel transaction
    fn cancel_transaction(&self, transaction_id: &str) -> Result<String, Box<dyn std::error::Error>> {
        let mut transactions = self.transaction_state.lock().unwrap();
        
        if let Some(transaction) = transactions.get_mut(transaction_id) {
            transaction.status = TransactionStatus::Cancelled;
            transaction.updated_at = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs();
            info!("Cancelled transaction: {}", transaction_id);
            Ok("Transaction cancelled successfully".to_string())
        } else {
            Err("Transaction not found".into())
        }
    }

    /// Get transaction status
    fn get_transaction_status(&self, transaction_id: &str) -> Result<String, Box<dyn std::error::Error>> {
        let transactions = self.transaction_state.lock().unwrap();
        
        if let Some(transaction) = transactions.get(transaction_id) {
            Ok(serde_json::to_string(transaction)?)
        } else {
            Err("Transaction not found".into())
        }
    }

    /// Stage deployment with enhanced features
    fn stage_deployment(&self, commit_checksum: &str, options_json: &str) -> Result<String, Box<dyn std::error::Error>> {
        let ostree_manager = self.ostree_manager.lock().unwrap();
        
        let options: apt_ostree::ostree::DeploymentOptions = if options_json.is_empty() {
            apt_ostree::ostree::DeploymentOptions {
                validate_packages: true,
                validate_filesystem: true,
                allow_downgrade: false,
                force: false,
            }
        } else {
            serde_json::from_str(options_json)?
        };
        
        let staged_deployment = tokio::runtime::Runtime::new()?.block_on(
            ostree_manager.stage_deployment(commit_checksum, &options)
        )?;
        
        Ok(serde_json::to_string(&staged_deployment)?)
    }

    /// Create package layer with enhanced features
    fn create_package_layer(&self, packages: &[String], options_json: &str) -> Result<String, Box<dyn std::error::Error>> {
        let ostree_manager = self.ostree_manager.lock().unwrap();
        
        let options: apt_ostree::ostree::LayerOptions = if options_json.is_empty() {
            apt_ostree::ostree::LayerOptions {
                execute_scripts: true,
                validate_dependencies: true,
                optimize_size: false,
            }
        } else {
            serde_json::from_str(options_json)?
        };
        
        let package_layer = tokio::runtime::Runtime::new()?.block_on(
            ostree_manager.create_package_layer(packages, &options)
        )?;
        
        Ok(serde_json::to_string(&package_layer)?)
    }

    /// Extract commit metadata with enhanced features
    fn extract_commit_metadata(&self, commit_checksum: &str) -> Result<String, Box<dyn std::error::Error>> {
        let ostree_manager = self.ostree_manager.lock().unwrap();
        
        let metadata = tokio::runtime::Runtime::new()?.block_on(
            ostree_manager.extract_commit_metadata(commit_checksum)
        )?;
        
        Ok(serde_json::to_string(&metadata)?)
    }
}

impl Clone for AptOstreeDaemon {
    fn clone(&self) -> Self {
        AptOstreeDaemon {
            ostree_manager: self.ostree_manager.clone(),
            apt_manager: self.apt_manager.clone(),
            package_manager: self.package_manager.clone(),
            performance_manager: self.performance_manager.clone(),
            transaction_state: self.transaction_state.clone(),
            system_status: self.system_status.clone(),
        }
    }
}

fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Initialize logging
    tracing_subscriber::fmt::init();
    
    info!("Starting apt-ostree D-Bus daemon...");
    
    // Create and run the daemon
    let daemon = AptOstreeDaemon::new()?;
    daemon.run()?;
    
    Ok(())
} 