from __future__ import annotations

import os
from pathlib import Path


CONFIG_DIR = Path.home() / ".config" / "sophnet-customer-management"
CONFIG_FILE = CONFIG_DIR / "config.env"
DEFAULT_DB_FILE = CONFIG_DIR / "customer_mgmt.sqlite3"
DB_PATH_KEY = "CUSTOMER_MGMT_DB_PATH"


def resolve_db_path(cli_db: str | None) -> Path:
    if cli_db:
        db_path = Path(cli_db).expanduser()
        persist_db_path(db_path)
        return db_path

    env_db = load_env_value(DB_PATH_KEY)
    if env_db:
        return Path(env_db).expanduser()

    default_db = DEFAULT_DB_FILE
    persist_db_path(default_db)
    return default_db


def persist_db_path(db_path: Path) -> None:
    CONFIG_DIR.mkdir(parents=True, exist_ok=True)
    entries = load_env_entries()
    entries[DB_PATH_KEY] = str(db_path.expanduser().resolve())
    lines = ["# sophnet-customer-management runtime config"]
    lines.extend(f"{key}={value}" for key, value in sorted(entries.items()))
    CONFIG_FILE.write_text("\n".join(lines) + "\n", encoding="utf-8")


def load_env_value(key: str) -> str | None:
    value = load_env_entries().get(key)
    if value:
        return value
    return os.environ.get(key)


def load_env_entries() -> dict[str, str]:
    if not CONFIG_FILE.exists():
        return {}
    entries: dict[str, str] = {}
    for raw_line in CONFIG_FILE.read_text(encoding="utf-8").splitlines():
        line = raw_line.strip()
        if not line or line.startswith("#") or "=" not in line:
            continue
        key, value = line.split("=", 1)
        entries[key.strip()] = value.strip()
    return entries
