import os
from pathlib import Path

ROOT = Path(__file__).resolve().parent.parent.parent


def _load_dotenv():
    # On shared hosting keep the secrets file OUTSIDE the app folder: <app folder>-data/.env is read first.
    for f in (ROOT.parent / (ROOT.name + "-data") / ".env", ROOT / ".env"):
        if f.exists():
            for line in f.read_text(encoding="utf-8").splitlines():
                line = line.strip()
                if line and not line.startswith("#") and "=" in line:
                    k, v = line.split("=", 1)
                    os.environ.setdefault(k.strip(), v.strip().strip('"'))


_load_dotenv()

DATABASE_URL = os.environ.get("DATABASE_URL", "postgresql+psycopg://postgres:devpass@127.0.0.1:55432/elitemart")
DEMO = os.environ.get("DEMO", "0") == "1"
COOKIE_SECURE = os.environ.get("COOKIE_SECURE", "0") == "1"
UPLOAD_DIR = Path(os.environ.get("UPLOAD_DIR", str(ROOT / "uploads")))
WEB_DIR = Path(os.environ.get("WEB_DIR", str(ROOT / "web" / "dist")))
SESSION_HOURS = 12

# One-time "make the first owner" page, for hosts with no terminal. Set a long random code in .env, open /owner,
# make the owner, then DELETE the line. The page also closes by itself once an owner exists.
SETUP_CODE = os.environ.get("SETUP_CODE", "").strip()

# Online payment. A Paystack secret key (sk_test_... or sk_live_...) switches real payment on.
# Without one, the demo shop uses a pretend payment page; a real store shows no online option.
PAYSTACK_SECRET_KEY = os.environ.get("PAYSTACK_SECRET_KEY", "").strip()
PUBLIC_URL = os.environ.get("PUBLIC_URL", "").rstrip("/")  # e.g. https://shop.example.com (used for the return link)
PAYMENT_PROVIDER = "paystack" if PAYSTACK_SECRET_KEY else ("demo" if DEMO else "")
UNPAID_HOLD_MINUTES = int(os.environ.get("UNPAID_HOLD_MINUTES", "60"))

_secret = os.environ.get("SECRET_KEY", "")
if not _secret:
    if DEMO or os.environ.get("TESTING") == "1" or "55432" in DATABASE_URL:
        _secret = "dev-only-secret-not-for-production-use-0123456789"
    else:
        raise RuntimeError("SECRET_KEY is not set. Put a long random value in .env.")
SECRET_KEY = _secret
