import os
from pathlib import Path

from flask import send_from_directory
from waitress import serve


BASE_DIR = Path(__file__).resolve().parent
UPLOAD_ROOT = BASE_DIR / "uploads"


def load_env_file(path: Path):
    if not path.exists():
        return

    for raw_line in path.read_text(encoding="utf-8").splitlines():
        line = raw_line.strip()

        if not line or line.startswith("#"):
            continue

        if line.startswith("export "):
            line = line[len("export "):].strip()

        if "=" not in line:
            continue

        key, value = line.split("=", 1)
        key = key.strip()
        value = value.strip().strip('"').strip("'")

        os.environ.setdefault(key, value)


load_env_file(BASE_DIR / ".env.runtime")

import app as app_module

app = app_module.app

app_module.AVATAR_UPLOAD_DIR = str(UPLOAD_ROOT / "avatars")
app_module.SITE_BRANDING_UPLOAD_DIR = str(UPLOAD_ROOT / "site")
app_module.PRODUCT_IMAGE_UPLOAD_DIR = str(UPLOAD_ROOT / "products")
app_module.PRODUCT_CONTENT_IMAGE_UPLOAD_DIR = str(UPLOAD_ROOT / "products" / "content")


@app.route("/uploads/<path:filename>")
def local_uploads(filename):
    return send_from_directory(UPLOAD_ROOT, filename)


if __name__ == "__main__":
    print("Local site running at: http://127.0.0.1:5000")
    print("Press Ctrl+C to stop.")
    serve(app, host="127.0.0.1", port=5000)
