#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from __future__ import annotations

import os
from datetime import datetime

import database
from app_config import get_config
from app_security import is_safe_path
from flask import Blueprint, jsonify, send_from_directory
from flask_login import current_user, login_required
from services.client_log import log_to_client
from services.time_utils import BEIJING_TZ

config = get_config()
SCREENSHOTS_DIR = config.SCREENSHOTS_DIR

api_screenshots_bp = Blueprint("api_screenshots", __name__)


@api_screenshots_bp.route("/api/screenshots", methods=["GET"])
@login_required
def get_screenshots():
    """获取当前用户的截图列表"""
    user_id = current_user.id
    user_info = database.get_user_by_id(user_id)
    username_prefix = user_info["username"] if user_info else f"user{user_id}"

    try:
        screenshots = []
        if os.path.exists(SCREENSHOTS_DIR):
            for filename in os.listdir(SCREENSHOTS_DIR):
                if filename.lower().endswith((".png", ".jpg", ".jpeg")) and filename.startswith(username_prefix + "_"):
                    filepath = os.path.join(SCREENSHOTS_DIR, filename)
                    stat = os.stat(filepath)
                    created_time = datetime.fromtimestamp(stat.st_mtime, tz=BEIJING_TZ)
                    parts = filename.rsplit(".", 1)[0].split("_", 1)
                    if len(parts) > 1:
                        display_name = parts[1] + "." + filename.rsplit(".", 1)[1]
                    else:
                        display_name = filename

                    screenshots.append(
                        {
                            "filename": filename,
                            "display_name": display_name,
                            "size": stat.st_size,
                            "created": created_time.strftime("%Y-%m-%d %H:%M:%S"),
                        }
                    )
        screenshots.sort(key=lambda x: x["created"], reverse=True)
        return jsonify(screenshots)
    except Exception as e:
        return jsonify({"error": str(e)}), 500


@api_screenshots_bp.route("/screenshots/<filename>")
@login_required
def serve_screenshot(filename):
    """提供截图文件访问"""
    user_id = current_user.id
    user_info = database.get_user_by_id(user_id)
    username_prefix = user_info["username"] if user_info else f"user{user_id}"

    if not filename.startswith(username_prefix + "_"):
        return jsonify({"error": "无权访问"}), 403

    if not is_safe_path(SCREENSHOTS_DIR, filename):
        return jsonify({"error": "非法路径"}), 403

    return send_from_directory(SCREENSHOTS_DIR, filename)


@api_screenshots_bp.route("/api/screenshots/<filename>", methods=["DELETE"])
@login_required
def delete_screenshot(filename):
    """删除指定截图"""
    user_id = current_user.id
    user_info = database.get_user_by_id(user_id)
    username_prefix = user_info["username"] if user_info else f"user{user_id}"

    if not filename.startswith(username_prefix + "_"):
        return jsonify({"error": "无权删除"}), 403

    try:
        filepath = os.path.join(SCREENSHOTS_DIR, filename)
        if os.path.exists(filepath):
            os.remove(filepath)
            log_to_client(f"删除截图: {filename}", user_id)
            return jsonify({"success": True})
        return jsonify({"error": "文件不存在"}), 404
    except Exception as e:
        return jsonify({"error": str(e)}), 500


@api_screenshots_bp.route("/api/screenshots/clear", methods=["POST"])
@login_required
def clear_all_screenshots():
    """清空当前用户的所有截图"""
    user_id = current_user.id
    user_info = database.get_user_by_id(user_id)
    username_prefix = user_info["username"] if user_info else f"user{user_id}"

    try:
        deleted_count = 0
        if os.path.exists(SCREENSHOTS_DIR):
            for filename in os.listdir(SCREENSHOTS_DIR):
                if filename.lower().endswith((".png", ".jpg", ".jpeg")) and filename.startswith(username_prefix + "_"):
                    filepath = os.path.join(SCREENSHOTS_DIR, filename)
                    os.remove(filepath)
                    deleted_count += 1
        log_to_client(f"清理了 {deleted_count} 个截图文件", user_id)
        return jsonify({"success": True, "deleted": deleted_count})
    except Exception as e:
        return jsonify({"error": str(e)}), 500

