"""
Flask 服务器 - 智途投送电脑端
提供静态文件服务 + REST API（士兵位置、危险区域）
浏览器通过 roslibjs 直接连接 rosbridge_server，无需 Python 后端处理无人机逻辑
"""

import os
from datetime import datetime
from flask import Flask, send_from_directory, request, jsonify

# 项目根目录（server 的上级目录）
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

app = Flask(__name__, static_folder=BASE_DIR)

# ---- 内存数据存储 ----
soldiers = {}       # { soldier_id: { id, name, lat, lng, updated_at } }
danger_zones = []   # [ { id, lat, lng, radius, description, created_at } ]
_danger_id_counter = 0


# ===== 静态文件路由 =====

@app.route("/")
def index():
    return send_from_directory(BASE_DIR, "index.html")


@app.route("/css/<path:filename>")
def css_files(filename):
    return send_from_directory(os.path.join(BASE_DIR, "css"), filename)


@app.route("/js/<path:filename>")
def js_files(filename):
    return send_from_directory(os.path.join(BASE_DIR, "js"), filename)


# ===== REST API: 士兵位置 =====

@app.route("/api/soldier/location", methods=["POST"])
def update_soldier_location():
    data = request.get_json(force=True)
    sid = data.get("id")
    if not sid:
        return jsonify({"ok": False, "error": "missing id"}), 400

    soldiers[sid] = {
        "id": sid,
        "name": data.get("name", sid),
        "lat": float(data.get("lat", 0)),
        "lng": float(data.get("lng", 0)),
        "updated_at": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    }
    return jsonify({"ok": True})


@app.route("/api/soldiers", methods=["GET"])
def get_soldiers():
    return jsonify({"soldiers": list(soldiers.values())})


# ===== REST API: 危险区域 =====

@app.route("/api/danger-zones", methods=["GET"])
def get_danger_zones():
    return jsonify({"danger_zones": danger_zones})


@app.route("/api/danger-zones", methods=["POST"])
def add_danger_zone():
    global _danger_id_counter
    data = request.get_json(force=True)
    _danger_id_counter += 1
    zone = {
        "id": _danger_id_counter,
        "lat": float(data.get("lat", 0)),
        "lng": float(data.get("lng", 0)),
        "radius": float(data.get("radius", 50)),
        "description": data.get("description", "危险区域"),
        "created_at": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    }
    danger_zones.append(zone)
    return jsonify({"ok": True, "id": zone["id"]})


if __name__ == "__main__":
    import sys
    import io
    sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
    print("=" * 50)
    print("  智途投送 - 物流保障系统")
    print("  http://localhost:5000")
    print("  实机 rosbridge: ws://192.168.1.14:9090")
    print("=" * 50)
    app.run(host="0.0.0.0", port=5000, debug=False)
