//! Feature marketplace and registry system

pub mod downloader;
pub mod publisher;
pub mod registry;
pub mod validator;

use std::collections::HashMap;

use rustelo_core::Result;
use serde::{Deserialize, Serialize};

#[derive(Debug, Serialize, Deserialize)]
pub struct MarketplaceConfig {
    pub registry_url: String,
    pub cache_path: String,
    pub verify_signatures: bool,
    pub trusted_publishers: Vec<String>,
}

impl Default for MarketplaceConfig {
    fn default() -> Self {
        Self {
            registry_url: "https://registry.rustelo.dev".to_string(),
            cache_path: "~/.rustelo/cache".to_string(),
            verify_signatures: true,
            trusted_publishers: vec!["rustelo-official".to_string()],
        }
    }
}

#[derive(Debug, Serialize, Deserialize)]
pub struct FeaturePackage {
    pub name: String,
    pub version: String,
    pub description: String,
    pub author: String,
    pub repository: Option<String>,
    pub license: String,
    pub dependencies: HashMap<String, String>,
    pub keywords: Vec<String>,
    pub checksum: String,
    pub signature: Option<String>,
}

pub struct MarketplaceClient {
    config: MarketplaceConfig,
    client: reqwest::Client,
}

impl MarketplaceClient {
    pub fn new(config: MarketplaceConfig) -> Self {
        Self {
            config,
            client: reqwest::Client::new(),
        }
    }

    pub async fn search_features(&self, query: &str) -> Result<Vec<FeaturePackage>> {
        let url = format!("{}/search?q={}", self.config.registry_url, query);
        let response = self.client.get(&url).send().await?;
        let packages: Vec<FeaturePackage> = response.json().await?;
        Ok(packages)
    }

    pub async fn get_feature(&self, name: &str, version: Option<&str>) -> Result<FeaturePackage> {
        let version = version.unwrap_or("latest");
        let url = format!("{}/features/{}/{}", self.config.registry_url, name, version);
        let response = self.client.get(&url).send().await?;
        let package: FeaturePackage = response.json().await?;
        Ok(package)
    }

    pub async fn download_feature(&self, package: &FeaturePackage) -> Result<Vec<u8>> {
        let url = format!(
            "{}/download/{}/{}",
            self.config.registry_url, package.name, package.version
        );
        let response = self.client.get(&url).send().await?;
        let bytes = response.bytes().await?;
        Ok(bytes.to_vec())
    }
}
