"""fearx-photos.sbxg.win 정적 파일 서버.

`/insta/{thread_id}/{nn}_image_{i}.jpg` 형태의 instagram thread 사진을 단첼린
(`https://danchelin.fearx.gg/`) 및 bootcamp(`https://bootcamp.fearx.gg/`)에
서빙. 본 서버는 8094에 바인드되고 cloudflared-fearx-photos 터널이 외부 노출.

2026-05-13 P1 단첼린 사진 최적화:
- 모든 .jpg 옆에 .webp variant (`scripts/convert_to_webp.py`) 사전 생성됨
- 요청이 `*.jpg` + `Accept: image/webp` 헤더 + 동명 `.webp` 존재 + size > 0
  이면 .webp를 image/webp MIME으로 응답. URL은 그대로 .jpg 유지
- 응답엔 항상 `Vary: Accept` 헤더 (CDN 캐싱 정합)
- 0-byte/누락 webp는 자동으로 jpg 폴백
"""
from flask import Flask, send_from_directory, abort, request, make_response
from flask_cors import CORS
from pathlib import Path
import os

ROOT = Path(r'C:\fearx-photos').resolve()
app = Flask(__name__)
CORS(app, resources={r"/*": {"origins": [
    "https://danchelin.fearx.gg",
    "https://bootcamp.fearx.gg",
]}})


def _listing(p: Path) -> str:
    items = sorted(os.listdir(p))
    links = []
    if p != ROOT:
        links.append('<a href="../">../</a>')
    for name in items:
        full = p / name
        href = name + ('/' if full.is_dir() else '')
        links.append(f'<a href="{href}">{href}</a>')
    return '<br>'.join(links)


def _webp_sibling(jpg: Path) -> Path | None:
    """Return the .webp path if it exists and is non-empty, else None."""
    if jpg.suffix.lower() != '.jpg':
        return None
    webp = jpg.with_suffix('.webp')
    try:
        if webp.is_file() and webp.stat().st_size > 0:
            return webp
    except OSError:
        return None
    return None


def _accepts_webp() -> bool:
    accept = request.headers.get('Accept', '')
    return 'image/webp' in accept


def _send_with_vary(directory: str, filename: str, mimetype: str | None = None):
    """send_from_directory wrapper that tacks on `Vary: Accept`."""
    if mimetype:
        resp = send_from_directory(directory, filename, mimetype=mimetype)
    else:
        resp = send_from_directory(directory, filename)
    resp.headers['Vary'] = 'Accept'
    return resp


@app.route('/', defaults={'subpath': ''})
@app.route('/<path:subpath>')
def serve(subpath):
    target = (ROOT / subpath).resolve() if subpath else ROOT
    try:
        target.relative_to(ROOT)
    except ValueError:
        abort(403)
    if target.is_dir():
        return _listing(target)
    if target.is_file():
        # Content-negotiation: serve .webp variant when caller advertises it
        webp = _webp_sibling(target) if _accepts_webp() else None
        if webp is not None:
            return _send_with_vary(str(webp.parent), webp.name, mimetype='image/webp')
        return _send_with_vary(str(target.parent), target.name)
    abort(404)


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8094, debug=False)
