from __future__ import annotations

import os
from pathlib import Path

DEFAULT_HOST = "127.0.0.1"
DEFAULT_PORT = 46291
DEFAULT_BROWSER = "chromium"

ENV_DAEMON_URL = "BROWSEABLE_DAEMON_URL"


def data_dir() -> Path:
    return Path.home() / ".browseable"


def pid_file() -> Path:
    return data_dir() / "daemon.pid"


def url_file() -> Path:
    return data_dir() / "daemon.url"


def log_file() -> Path:
    return data_dir() / "daemon.log"


def ensure_data_dir() -> Path:
    directory = data_dir()
    directory.mkdir(parents=True, exist_ok=True)
    return directory


def make_daemon_url(host: str = DEFAULT_HOST, port: int = DEFAULT_PORT) -> str:
    return f"http://{host}:{port}"


def get_daemon_url() -> str:
    override = os.environ.get(ENV_DAEMON_URL)
    if override:
        return override
    state_file = url_file()
    if state_file.exists():
        value = state_file.read_text(encoding="utf-8").strip()
        if value:
            return value
    return make_daemon_url()
