//! Python bindings for MCP (Model Context Protocol) configuration

use pyo3::prelude::*;

use flowgentra_ai::core::mcp::{MCPConfig, MCPConnectionType};

use crate::error::to_py_err;

// ─── PyMCPConfig ────────────────────────────────────────────────────────────

/// MCP (Model Context Protocol) configuration.
///
/// Example:
///     # SSE connection
///     mcp = MCPConfig.sse("http://localhost:8080/sse", name="my-server")
///
///     # Stdio connection
///     mcp = MCPConfig.stdio("npx", ["-y", "@modelcontextprotocol/server-filesystem", "/tmp"])
#[pyclass(name = "MCPConfig")]
#[derive(Clone)]
pub struct PyMCPConfig {
    pub(crate) inner: MCPConfig,
}

#[pymethods]
impl PyMCPConfig {
    /// Create an SSE (Server-Sent Events) connection config.
    #[staticmethod]
    #[pyo3(signature = (url, name=None))]
    fn sse(url: &str, name: Option<&str>) -> PyResult<Self> {
        let mut builder = MCPConfig::builder().sse(url);
        if let Some(n) = name {
            builder = builder.name(n);
        }
        let config = builder.build().map_err(to_py_err)?;
        Ok(PyMCPConfig { inner: config })
    }

    /// Create a Stdio connection config.
    #[staticmethod]
    #[pyo3(signature = (command, args=None, name=None))]
    fn stdio(command: &str, args: Option<Vec<String>>, name: Option<&str>) -> PyResult<Self> {
        let mut builder = MCPConfig::builder().stdio(command);
        if let Some(a) = args {
            builder = builder.args(a);
        }
        if let Some(n) = name {
            builder = builder.name(n);
        }
        let config = builder.build().map_err(to_py_err)?;
        Ok(PyMCPConfig { inner: config })
    }

    /// Create a Docker connection config.
    #[staticmethod]
    #[pyo3(signature = (image, name=None))]
    fn docker(image: &str, name: Option<&str>) -> PyResult<Self> {
        let mut builder = MCPConfig::builder().docker(image);
        if let Some(n) = name {
            builder = builder.name(n);
        }
        let config = builder.build().map_err(to_py_err)?;
        Ok(PyMCPConfig { inner: config })
    }

    /// Check if this is a remote connection.
    fn is_remote(&self) -> bool {
        self.inner.connection_type.is_remote()
    }

    /// Check if this is a local connection.
    fn is_local(&self) -> bool {
        self.inner.connection_type.is_local()
    }

    #[getter]
    fn name(&self) -> String {
        self.inner.name.clone()
    }

    fn __repr__(&self) -> String {
        let conn_type = match self.inner.connection_type {
            MCPConnectionType::Sse => "sse",
            MCPConnectionType::Stdio => "stdio",
            MCPConnectionType::Docker => "docker",
        };
        format!("MCPConfig(type='{}', name='{}')", conn_type, self.inner.name)
    }
}
