"""Run the unmodified Photoshot API smoke script against a private loopback worker."""
import hashlib
import os
from pathlib import Path
import shutil
import socket
import subprocess
import sys
import tempfile
import time
from urllib.request import urlopen
from service.models import CHECKSUMS

FINISHED = Path(__file__).resolve().parent
LAB = FINISHED.parent
PHOTO = LAB / "fixtures" / "astronaut.png"


def run():
    with tempfile.TemporaryDirectory(prefix="retouch-ep04-", ignore_cleanup_errors=True) as folder:
        root = Path(folder)
        runtime = root / "runtime"
        shutil.copytree(FINISHED, runtime, ignore=shutil.ignore_patterns("__pycache__"))
        input_photo = root / "astronaut.png"
        shutil.copyfile(PHOTO, input_photo)
        models = Path(os.getenv("RETOUCH_MODELS", str(LAB / ".models")))
        staged_models = root / "models"
        staged_models.mkdir()
        for name, expected in CHECKSUMS.items():
            source = models / name
            if not source.is_file():
                raise FileNotFoundError(f"{source} is missing. Install the pinned MediaPipe files first.")
            if hashlib.sha256(source.read_bytes()).hexdigest() != expected:
                raise ValueError(f"Model SHA-256 mismatch for {name}")
            shutil.copyfile(source, staged_models / name)
        env = os.environ.copy()
        env["RETOUCH_DATA"] = str(root / "data")
        env["RETOUCH_MODELS"] = str(staged_models)
        for key in ("RETOUCH_TOKEN", "RETOUCH_COMPANION"):
            env.pop(key, None)
        with socket.socket() as listener:
            listener.bind(("127.0.0.1", 0))
            port = listener.getsockname()[1]
        env["RETOUCH_LOOPBACK_PORT"] = str(port)
        base = f"http://127.0.0.1:{port}"
        log_file = Path(folder) / "worker.log"
        with log_file.open("wb") as log:
            command = [sys.executable, "-m", "uvicorn", "service.api:app", "--host", "127.0.0.1", "--port", str(port)]
            worker = subprocess.Popen(command, cwd=runtime, env=env, stdout=log, stderr=subprocess.STDOUT)
            try:
                for _ in range(100):
                    try:
                        with urlopen(base + "/v1/tools", timeout=1) as response:
                            if response.status == 200:
                                break
                    except OSError:
                        if worker.poll() is not None:
                            raise RuntimeError(log_file.read_text(errors="replace"))
                        time.sleep(.2)
                else:
                    raise RuntimeError("Local worker failed to start.")
                smoke = subprocess.run(
                    [sys.executable, "tests/smoke.py", str(input_photo), "--base", base],
                    cwd=runtime, env=env, capture_output=True, text=True, timeout=180,
                )
                (LAB / "verification" / "api-smoke.txt").write_text(
                    smoke.stdout + smoke.stderr + f"Exit code: {smoke.returncode}\n", encoding="utf-8")
                print(smoke.stdout)
                if smoke.returncode:
                    raise RuntimeError(smoke.stderr + log_file.read_text(errors="replace"))
            finally:
                worker.terminate()
                worker.wait(timeout=10)


if __name__ == "__main__":
    run()

