"""Resolve deploy URL prefix (subfolder) from environment and optional file."""

from __future__ import annotations

import os
from pathlib import Path


def _strip_subpath_value(raw: str) -> str:
    return raw.strip().strip("/")


def _candidate_deploy_subpath_files() -> list[Path]:
    here = Path(__file__).resolve().parent
    root = here.parent
    return [
        here / "deploy_subpath.txt",
        root / "DEPLOY_SUBPATH.txt",
    ]


def deploy_subpath_from_file(path: Path | None = None) -> str:
    """First non-empty, non-comment line from optional deploy files (see candidates)."""
    paths = [path] if path is not None else _candidate_deploy_subpath_files()
    for candidate in paths:
        try:
            text = candidate.read_text(encoding="utf-8")
        except OSError:
            continue
        for line in text.splitlines():
            line = line.strip()
            if line and not line.startswith("#"):
                return _strip_subpath_value(line)
    return ""


def resolve_site_subpath() -> str:
    """
    Folder segment only (no slashes), e.g. ```` for ``/``.

    Order: ``SITE_SUBPATH``, ``DJANGO_SITE_SUBPATH``, ``FORCE_DEPLOY_SUBPATH``,
    then ``mysite/deploy_subpath.txt`` or project-root ``DEPLOY_SUBPATH.txt``
    (for hosts where env is unreliable; upload via FTP if the panel does not apply env).
    Re-call on each request in middleware so panel env changes apply without relying
    on stale ``settings.SITE_SUBPATH`` import-time cache.
    """
    for key in ("SITE_SUBPATH", "DJANGO_SITE_SUBPATH", "FORCE_DEPLOY_SUBPATH"):
        s = _strip_subpath_value(os.environ.get(key, ""))
        if s:
            return s
    return deploy_subpath_from_file()
