import os

from flask import Flask, request

app = Flask(__name__)

_mode = "normal"
_annotations: list = []
_media_store: dict = {}


def _fail():
    return _mode == "error"


@app.route("/annotations", methods=["POST"])
def annotations():
    if _fail():
        return "", 503
    _annotations.append(request.get_json(silent=True))
    return "", 200


@app.route("/auth/refresh", methods=["POST"])
def auth_refresh():
    if _fail():
        return "", 503
    return {"token": "refreshed-test-token"}


@app.route("/api/users/<user_id>/ai-settings", methods=["GET"])
def user_ai_settings(user_id):
    if _fail():
        return "", 503
    return {
        "frame_period_recognition": 4,
        "frame_recognition_seconds": 2,
        "probability_threshold": 0.25,
        "tracking_distance_confidence": 0.1,
        "tracking_probability_increase": 0.1,
        "tracking_intersection_threshold": 0.6,
        "model_batch_size": 8,
        "big_image_tile_overlap_percent": 20,
        "altitude": 400,
        "focal_length": 24,
        "sensor_width": 23.5,
    }


@app.route("/api/media", methods=["POST"])
def create_media():
    if _fail():
        return "", 503
    body = request.get_json(silent=True) or {}
    mid = body.get("id")
    if not mid:
        return "", 400
    _media_store[str(mid)] = dict(body)
    return body, 201


@app.route("/api/media/<media_id>/status", methods=["PUT"])
def update_media_status(media_id):
    if _fail():
        return "", 503
    body = request.get_json(silent=True) or {}
    st = body.get("mediaStatus")
    key = str(media_id)
    rec = _media_store.get(key)
    if rec is None:
        rec = {"id": key}
        _media_store[key] = rec
    if st is not None:
        rec["mediaStatus"] = st
    return "", 204


@app.route("/api/media/<media_id>", methods=["GET"])
def media_path(media_id):
    if _fail():
        return "", 503
    key = str(media_id)
    rec = _media_store.get(key)
    if rec and rec.get("path"):
        return {"path": rec["path"]}
    root = os.environ.get("MEDIA_DIR", "/media")
    if key.startswith("sse-") or key.startswith("video-"):
        return {"path": f"{root}/video_test01.mp4"}
    return {"path": f"{root}/image_small.jpg"}


@app.route("/mock/config", methods=["POST"])
def mock_config():
    global _mode
    body = request.get_json(silent=True) or {}
    mode = body.get("mode", "normal")
    if mode not in ("normal", "error"):
        return "", 400
    _mode = mode
    return "", 200


@app.route("/mock/reset", methods=["POST"])
def mock_reset():
    global _mode, _annotations, _media_store
    _mode = "normal"
    _annotations.clear()
    _media_store.clear()
    return "", 200


@app.route("/mock/status", methods=["GET"])
def mock_status():
    return {
        "mode": _mode,
        "annotation_count": len(_annotations),
        "annotations": list(_annotations),
        "media_count": len(_media_store),
    }


@app.route("/mock/annotations", methods=["GET"])
def mock_annotations_list():
    return {"annotations": list(_annotations)}


@app.route("/mock/media", methods=["GET"])
def mock_media_list():
    return {"media": dict(_media_store)}
