portal-handler 0.1.0

System URI handler for portal.nvim — forwards nvim:// URIs to a running Neovim instance via RPC
//! portal-handler — CLI Rust pour portal.nvim
//!
//! Sous-commandes :
//!   open <URI>    Reçoit une URI nvim:// depuis l'OS et l'envoie à Neovim via RPC
//!   install       Enregistre le schéma nvim:// dans le système (Linux/macOS/Windows)
//!   uninstall     Dé-enregistre
//!   list          Liste les sockets Neovim actifs

mod install;
mod socket;
mod uri;

use anyhow::Result;
use clap::{Parser, Subcommand};

/// portal-handler : système de deep-link nvim:// pour Neovim
#[derive(Debug, Parser)]
#[command(
    name    = "portal-handler",
    version = "0.1.0",
    about   = "Forward les URIs nvim:// vers une instance Neovim active via RPC"
)]
struct Cli {
    #[command(subcommand)]
    command: Commands,
}

#[derive(Debug, Subcommand)]
enum Commands {
    /// Ouvre une URI nvim:// dans Neovim (appelé automatiquement par l'OS)
    Open {
        /// L'URI à traiter, ex: nvim://open?file=/chemin/fichier.rs&line=42
        uri: String,

        /// Chemin du socket Neovim (override l'auto-détection)
        #[arg(long, short = 's')]
        socket: Option<String>,
    },

    /// Enregistre le handler nvim:// dans le système
    Install {
        /// Chemin du binaire à enregistrer (défaut: binaire courant)
        #[arg(long)]
        binary: Option<String>,
    },

    /// Dé-enregistre le handler nvim://
    Uninstall,

    /// Liste les instances Neovim actives et leurs sockets
    List,
}

#[tokio::main]
async fn main() -> Result<()> {
    let cli = Cli::parse();

    match cli.command {
        Commands::Open { uri, socket } => {
            uri::handle(&uri, socket.as_deref()).await?;
        }

        Commands::Install { binary } => {
            let bin = binary.unwrap_or_else(|| {
                std::env::current_exe()
                    .expect("impossible de lire le chemin du binaire courant")
                    .to_string_lossy()
                    .into_owned()
            });
            install::install(&bin)?;
            println!("✓ handler nvim:// enregistré dans le système");
        }

        Commands::Uninstall => {
            install::uninstall()?;
            println!("✓ handler nvim:// dé-enregistré");
        }

        Commands::List => {
            let sockets = socket::find_all();
            if sockets.is_empty() {
                println!("Aucune instance Neovim active trouvée.");
            } else {
                println!("Instances Neovim actives ({}) :", sockets.len());
                for s in &sockets {
                    println!("  {}", s.display());
                }
            }
        }
    }

    Ok(())
}