"""Local credential storage for mldash.

Credentials are stored as JSON in ~/.config/mldash/credentials (or $MLDASH_CONFIG_DIR).
Format:
{
    "url": "https://api.mldash.com",
    "api_key": "mldash_xxx",
    "project_id": 5
}
"""

import json
import os
import stat

_CONFIG_DIR_ENV = 'MLDASH_CONFIG_DIR'
_DEFAULT_DIR = os.path.join(os.path.expanduser('~'), '.config', 'mldash')
_CREDENTIALS_FILE = 'credentials'


def _config_dir():
    return os.environ.get(_CONFIG_DIR_ENV, _DEFAULT_DIR)


def _credentials_path():
    return os.path.join(_config_dir(), _CREDENTIALS_FILE)


def load():
    """Load stored credentials. Returns a dict (empty if no file exists)."""
    path = _credentials_path()
    if not os.path.isfile(path):
        return {}
    try:
        with open(path, 'r') as f:
            return json.load(f)
    except (json.JSONDecodeError, OSError):
        return {}


def store(url=None, api_key=None, project_id=None):
    """Save credentials to disk. Only overwrites fields that are provided."""
    existing = load()
    if url is not None:
        existing['url'] = url
    if api_key is not None:
        existing['api_key'] = api_key
    if project_id is not None:
        existing['project_id'] = project_id

    directory = _config_dir()
    os.makedirs(directory, exist_ok=True)

    path = _credentials_path()
    with open(path, 'w') as f:
        json.dump(existing, f, indent=2)

    # Restrict file permissions to owner only (chmod 600)
    try:
        os.chmod(path, stat.S_IRUSR | stat.S_IWUSR)
    except OSError:
        pass  # Windows or other systems where this fails


def clear():
    """Remove stored credentials file."""
    path = _credentials_path()
    if os.path.isfile(path):
        os.unlink(path)


def get(key, default=None):
    """Read a single field from stored credentials."""
    return load().get(key, default)
