import json
import os
from pathlib import Path
from typing import Optional

CONFIG_FILE = Path.home() / ".notilens_config.json"


def read_config() -> dict:
    if not CONFIG_FILE.exists():
        return {}
    try:
        return json.loads(CONFIG_FILE.read_text())
    except Exception:
        return {}


def write_config(config: dict) -> None:
    CONFIG_FILE.write_text(json.dumps(config, indent=2))


def get_agent_config(agent: str) -> Optional[dict]:
    return read_config().get(agent)


def add_agent(agent: str, transport: str, endpoint: str, secret: str) -> None:
    config = read_config()
    config[agent] = {"transport": transport, "endpoint": endpoint, "secret": secret}
    write_config(config)
