"""
FASHN VTON v1.5 GPU server (Apache-2.0 model, runs on YOUR machine).

Run it on a computer with an NVIDIA GPU (the model page says ~8 GB VRAM). Django sends it a
person photo + garment photo and gets a JPEG back. Keeping it separate means the GPU machine
can be different from the web server, and its libraries never clash with the web app's.

    python server.py            # listens on 0.0.0.0:5001
Settings can be typed in the window ($env:NAME="value") OR written in fashn_server/.env
(copy .env.example to .env). Environment:
    FASHN_WEIGHTS_DIR  folder with the downloaded weights (default ./weights)
    FASHN_API_KEY      shared secret; Django sends it in the X-Api-Key header
    FASHN_DUMMY=1      no model: returns the person photo unchanged (only to test the wiring)
    FASHN_HOST         address to listen on (default 127.0.0.1 = this computer only)
"""
import io
import os
import sys
import threading
import time


def _load_env_file():
    """Read fashn_server/.env (KEY=VALUE per line) so you do not have to type $env:... every time.
    Values already set in the window win over the file."""
    path = os.path.join(os.path.dirname(os.path.abspath(__file__)), ".env")
    if not os.path.exists(path):
        return
    with open(path, encoding="utf-8") as handle:
        for line in handle:
            line = line.strip()
            if not line or line.startswith("#") or "=" not in line:
                continue
            key, value = line.split("=", 1)
            os.environ.setdefault(key.strip(), value.strip().strip('"').strip("'"))


_load_env_file()

from flask import Flask, Response, jsonify, request  # noqa: E402
from PIL import Image, ImageOps

app = Flask(__name__)
app.config["MAX_CONTENT_LENGTH"] = 25 * 1024 * 1024

CATEGORIES = {"tops", "bottoms", "one-pieces"}
_pipeline = None
_gpu_lock = threading.Lock()  # one try-on at a time: a small GPU cannot run two


class _DummyPipeline:
    """Stand-in used by FASHN_DUMMY=1."""
    def __call__(self, person_image, garment_image, category):
        return type("Result", (), {"images": [person_image]})()


def get_pipeline():
    global _pipeline
    if _pipeline is None:
        if os.getenv("FASHN_DUMMY") == "1":
            _pipeline = _DummyPipeline()
        else:
            print("Loading the AI model (first photo only; can take a few minutes on a CPU)...", flush=True)
            started = time.time()
            from fashn_vton import TryOnPipeline  # installed from the official repo (see README)
            _pipeline = TryOnPipeline(weights_dir=os.getenv("FASHN_WEIGHTS_DIR", "./weights"))
            print(f"AI model loaded in {time.time() - started:.0f} s.", flush=True)
    return _pipeline


def _load(file_storage):
    return ImageOps.exif_transpose(Image.open(file_storage.stream)).convert("RGB")


@app.get("/health")
def health():
    return jsonify(status="ok", dummy=os.getenv("FASHN_DUMMY") == "1")


@app.post("/tryon")
def tryon():
    key = os.getenv("FASHN_API_KEY", "")
    if key and request.headers.get("X-Api-Key") != key:
        return jsonify(error="Invalid API key."), 401
    category = request.form.get("category", "one-pieces")
    if category not in CATEGORIES:
        return jsonify(error=f"category must be one of {sorted(CATEGORIES)}"), 400
    if "person" not in request.files or "garment" not in request.files:
        return jsonify(error="Send 'person' and 'garment' images."), 400
    try:
        person, garment = _load(request.files["person"]), _load(request.files["garment"])
    except Exception:  # noqa: BLE001
        return jsonify(error="Could not read the images."), 400

    try:
        with _gpu_lock:
            print(f"Try-on started ({category}, photo {person.width}x{person.height}). Please wait...", flush=True)
            started = time.time()
            result = get_pipeline()(person_image=person, garment_image=garment, category=category)
            print(f"Try-on finished in {time.time() - started:.0f} s.", flush=True)
    except Exception as exc:  # noqa: BLE001 - tell the website WHY, and keep the full details in this window
        app.logger.exception("Try-on failed")
        return jsonify(error=f"{type(exc).__name__}: {exc}"[:300]), 500
    buf = io.BytesIO()
    result.images[0].convert("RGB").save(buf, format="JPEG", quality=92)
    return Response(buf.getvalue(), mimetype="image/jpeg")


if __name__ == "__main__":
    if os.getenv("FASHN_DUMMY") != "1":
        try:
            import fashn_vton  # noqa: F401
        except ImportError:
            print("\nERROR: the 'fashn_vton' model is not installed in THIS Python environment:")
            print("   " + sys.executable)
            print("Activate the AI environment first (the one where you ran 'pip install -e .'):")
            print("   cd <folder>\\fashn-vton-1.5   then   .venv\\Scripts\\Activate.ps1")
            print("The prompt must start with (.venv), not (venv). Then start this server again.\n")
            sys.exit(1)
    # Listen only on this computer by default. Set FASHN_HOST=0.0.0.0 only if the website runs on another machine.
    app.run(host=os.getenv("FASHN_HOST", "127.0.0.1"), port=int(os.getenv("PORT", "5001")), threaded=True)
