from __future__ import annotations

import os
from pathlib import Path

from platformdirs import user_cache_dir


APP_NAME = "awspipe"


def app_home() -> Path:
    override = os.environ.get("AWSPIPE_HOME")
    if override:
        return Path(override).expanduser()
    return Path(user_cache_dir(APP_NAME, appauthor=False))


def fallback_app_home() -> Path:
    return Path.cwd() / ".awspipe"


def ensure_app_home() -> Path:
    primary = app_home()
    try:
        primary.mkdir(parents=True, exist_ok=True)
        return primary
    except OSError:
        fallback = fallback_app_home()
        fallback.mkdir(parents=True, exist_ok=True)
        return fallback


def database_path() -> Path:
    return ensure_app_home() / "awspipe.duckdb"
