import os
import tomllib
import tomli_w
from platformdirs import user_config_dir

CONFIG_DIR = user_config_dir("archo")
CONFIG_PATH = os.path.join(CONFIG_DIR, "config.toml")

def config_exists() -> bool:
    """Check if config file exists."""
    return os.path.exists(CONFIG_PATH)

def setup_config(provider: str, model: str, api_key: str, host_url: str = None) -> None:
    """Setup .archo/config file"""
    if not config_exists():

        os.makedirs(CONFIG_DIR, exist_ok=True)

        with open(CONFIG_PATH, "x") as f:
            f.write("[llm-setup]\n")
            f.write(f'LLM_PROVIDER = "{provider}"\n')
            f.write(f'LLM_MODEL = "{model}"\n')
            f.write(f'LLM_API_KEY= "{api_key}"\n')
            if host_url:
                f.write(f'OLLAMA_HOST= "{host_url}"\n')

def get_config() -> dict:
    """Get .archo/config file"""
    if config_exists():
        with open(CONFIG_PATH, "rb") as config_file:
            try:
                config_dict = tomllib.load(config_file)
            except tomllib.TOMLDecodeError:
                raise ValueError("Config file is corrupted")

        return config_dict
    raise FileNotFoundError("Config file not found")

def update_config(config: dict) -> None:
    """Update .archo/config file"""
    with open(CONFIG_PATH, "wb") as config_file:
        tomli_w.dump(config, config_file)

def get_model() -> str:
    """Get current model from config file"""
    config = get_config()
    return config.get("llm-setup", {}).get("LLM_MODEL", "No model set")

def get_provider() -> str:
    """Get current provider from config file"""
    config = get_config()
    return config.get("llm-setup", {}).get("LLM_PROVIDER", "No provider set")

def update_model(model: str) -> None:
    """Update current model from config file"""
    config = get_config()
    config["llm-setup"]["LLM_MODEL"] = model
    update_config(config)

def update_provider(provider: str) -> None:
    """Update current provider from config file"""
    config = get_config()
    config["llm-setup"]["LLM_PROVIDER"] = provider
    update_config(config)

def get_api_key() -> str:
    """Get current API key from config file"""
    config = get_config()
    return config.get("llm-setup", {}).get("LLM_API_KEY", "No API key set")

def update_api_key(api_key: str) -> None:
    """Update current API key in config file"""
    config = get_config()
    config["llm-setup"]["LLM_API_KEY"] = api_key
    update_config(config)

def get_llm_host() -> str | None:
    """Get current Ollama host URL from config file, or None if not set"""
    config = get_config()
    return config.get("llm-setup", {}).get("OLLAMA_HOST", None)

def update_llm_host(host_url: str) -> None:
    """Update current Ollama host URL in config file"""
    config = get_config()
    config["llm-setup"]["OLLAMA_HOST"] = host_url
    update_config(config)


