"""User configuration — persistent settings for axm-bib.

Stores configuration in ``~/.config/axm-bib/config.toml``.
Resolves values with priority: env var > config file > interactive prompt.
"""

from __future__ import annotations

import os
import sys
from pathlib import Path

__all__ = ["get_email", "resolve_email"]

_CONFIG_DIR = Path.home() / ".config" / "axm-bib"
_CONFIG_FILE = _CONFIG_DIR / "config.toml"


def _read_config() -> dict[str, str]:
    """Read the config file, returning empty dict if missing."""
    if not _CONFIG_FILE.exists():
        return {}

    data: dict[str, str] = {}
    for line in _CONFIG_FILE.read_text().splitlines():
        line = line.strip()
        if "=" in line and not line.startswith("#"):
            key, _, value = line.partition("=")
            data[key.strip()] = value.strip().strip('"').strip("'")
    return data


def _write_config(key: str, value: str) -> None:
    """Write a key=value to the config file, preserving existing entries."""
    _CONFIG_DIR.mkdir(parents=True, exist_ok=True)

    config = _read_config()
    config[key] = value

    lines = [f'{k} = "{v}"' for k, v in sorted(config.items())]
    _CONFIG_FILE.write_text("\n".join(lines) + "\n")


def get_email() -> str | None:
    """Get email from env var or config file (no prompt).

    Returns:
        Email string or None if not configured.
    """
    # 1. Env var takes priority
    env_email = os.environ.get("UNPAYWALL_EMAIL", "").strip()
    if env_email:
        return env_email

    # 2. Config file
    config = _read_config()
    return config.get("email") or None


def resolve_email(*, interactive: bool = True) -> str:
    """Resolve email, prompting interactively if needed.

    Args:
        interactive: If True, prompt user when email is not configured.

    Returns:
        Email string.

    Raises:
        SystemExit: If no email available and not interactive.
    """
    email = get_email()
    if email:
        return email

    if not interactive or not sys.stdin.isatty():
        print(
            "Error: No email configured for Unpaywall API.\n"
            "Set UNPAYWALL_EMAIL env var or run interactively.",
            file=sys.stderr,
        )
        raise SystemExit(1)

    # Interactive prompt
    print("axm-bib needs an email for the Unpaywall API (free, no registration).")
    email = input("Your email: ").strip()

    if not email or "@" not in email:
        print("Error: Invalid email.", file=sys.stderr)
        raise SystemExit(1)

    # Save for future use
    _write_config("email", email)
    print(f"Saved to {_CONFIG_FILE}")

    return email
