use serde_json::json;
use tauri::{AppHandle, Runtime};
use tauri_plugin_store::StoreExt;

use crate::agent::{
    default_task_defaults, AgentStoredSettings, RemoteProviderSettings, AGENT_SETTINGS_STORE_PATH,
    DEFAULT_REMOTE_BASE_URL, DEFAULT_REMOTE_MODEL,
};
use crate::error::AppError;

const REMOTE_ENABLED_KEY: &str = "remoteEnabled";
const REMOTE_BASE_URL_KEY: &str = "remoteBaseUrl";
const REMOTE_API_KEY_KEY: &str = "remoteApiKey";
const DEFAULT_REMOTE_MODEL_KEY: &str = "defaultRemoteModel";
const TASK_DEFAULTS_KEY: &str = "taskDefaults";
const SEC_EDGAR_USER_AGENT_KEY: &str = "secEdgarUserAgent";
const LEGACY_BASE_URL_KEY: &str = "baseUrl";
const LEGACY_MODEL_KEY: &str = "model";
const LEGACY_API_KEY_KEY: &str = "apiKey";
const LOCAL_ENABLED_KEY: &str = "localEnabled";
const LOCAL_BASE_URL_KEY: &str = "localBaseUrl";
const LOCAL_AVAILABLE_MODELS_KEY: &str = "localAvailableModels";

/// Manages the provider settings and plaintext API key stored through the Tauri store plugin.
#[derive(Debug)]
pub struct AgentSettingsService<R: Runtime> {
    app_handle: AppHandle<R>,
}

impl<R: Runtime> Clone for AgentSettingsService<R> {
    fn clone(&self) -> Self {
        Self {
            app_handle: self.app_handle.clone(),
        }
    }
}

impl<R: Runtime> AgentSettingsService<R> {
    pub fn new(app_handle: &AppHandle<R>) -> Self {
        Self {
            app_handle: app_handle.clone(),
        }
    }

    pub fn load(&self) -> Result<AgentStoredSettings, AppError> {
        let store = self
            .app_handle
            .store(AGENT_SETTINGS_STORE_PATH)
            .map_err(|error| AppError::SettingsStore(error.to_string()))?;

        let default_remote_model = store
            .get(DEFAULT_REMOTE_MODEL_KEY)
            .and_then(|value| value.as_str().map(ToOwned::to_owned))
            .or_else(|| {
                store
                    .get(LEGACY_MODEL_KEY)
                    .and_then(|value| value.as_str().map(ToOwned::to_owned))
            })
            .unwrap_or_else(|| DEFAULT_REMOTE_MODEL.to_string());

        let task_defaults = store
            .get(TASK_DEFAULTS_KEY)
            .and_then(|value| serde_json::from_value(value.clone()).ok())
            .unwrap_or_else(|| default_task_defaults(&default_remote_model));

        Ok(AgentStoredSettings {
            remote: RemoteProviderSettings {
                enabled: store
                    .get(REMOTE_ENABLED_KEY)
                    .and_then(|value| value.as_bool())
                    .unwrap_or(true),
                base_url: store
                    .get(REMOTE_BASE_URL_KEY)
                    .and_then(|value| value.as_str().map(ToOwned::to_owned))
                    .or_else(|| {
                        store
                            .get(LEGACY_BASE_URL_KEY)
                            .and_then(|value| value.as_str().map(ToOwned::to_owned))
                    })
                    .unwrap_or_else(|| DEFAULT_REMOTE_BASE_URL.to_string()),
                api_key: store
                    .get(REMOTE_API_KEY_KEY)
                    .and_then(|value| value.as_str().map(ToOwned::to_owned))
                    .or_else(|| {
                        store
                            .get(LEGACY_API_KEY_KEY)
                            .and_then(|value| value.as_str().map(ToOwned::to_owned))
                    })
                    .unwrap_or_default(),
            },
            default_remote_model,
            task_defaults,
            sec_edgar_user_agent: store
                .get(SEC_EDGAR_USER_AGENT_KEY)
                .and_then(|value| value.as_str().map(ToOwned::to_owned))
                .unwrap_or_default(),
        })
    }

    pub fn save(&self, settings: AgentStoredSettings) -> Result<AgentStoredSettings, AppError> {
        self.save_inner(&settings)?;
        Ok(settings)
    }

    pub fn set_remote_api_key(&self, api_key: String) -> Result<AgentStoredSettings, AppError> {
        let mut settings = self.load()?;
        settings.remote.api_key = api_key;
        self.save_inner(&settings)?;
        Ok(settings)
    }

    fn save_inner(&self, settings: &AgentStoredSettings) -> Result<(), AppError> {
        let store = self
            .app_handle
            .store(AGENT_SETTINGS_STORE_PATH)
            .map_err(|error| AppError::SettingsStore(error.to_string()))?;

        store.set(
            REMOTE_ENABLED_KEY.to_string(),
            json!(settings.remote.enabled),
        );
        store.set(
            REMOTE_BASE_URL_KEY.to_string(),
            json!(settings.remote.base_url),
        );
        store.set(
            REMOTE_API_KEY_KEY.to_string(),
            json!(settings.remote.api_key),
        );
        store.set(
            DEFAULT_REMOTE_MODEL_KEY.to_string(),
            json!(settings.default_remote_model),
        );
        store.set(TASK_DEFAULTS_KEY.to_string(), json!(settings.task_defaults));
        store.set(
            SEC_EDGAR_USER_AGENT_KEY.to_string(),
            json!(settings.sec_edgar_user_agent),
        );

        store.delete(LOCAL_ENABLED_KEY);
        store.delete(LOCAL_BASE_URL_KEY);
        store.delete(LOCAL_AVAILABLE_MODELS_KEY);
        store.delete(LEGACY_BASE_URL_KEY);
        store.delete(LEGACY_MODEL_KEY);
        store.delete(LEGACY_API_KEY_KEY);

        store
            .save()
            .map_err(|error| AppError::SettingsStore(error.to_string()))
    }
}
