from flask import Blueprint, request, jsonify
import os, subprocess
from helpers.db import db_get_video
from helpers.favorites import db_toggle_fav, db_get_fav_set
from config import get_local_db_connection

api = Blueprint("api", __name__)

@api.route('/open-folder', methods=['POST'])
def open_folder():
    data = request.json
    file_path = data.get("file_path")
    file_path = os.path.abspath(file_path)
    dir_path = os.path.dirname(file_path)

    if not file_path or not os.path.exists(file_path):
        return jsonify({"error": "File not found"}), 404

    # Open folder in Explorer and select file
    subprocess.run(f'explorer {dir_path}')
    return jsonify({"success": True})


@api.route("/api/fav/toggle/<video_id>", methods=["POST"])
def api_fav_toggle(video_id):
    # Optional: validate video exists
    try:
        _ = db_get_video(video_id)
    except Exception:
        return jsonify({"error": "video not found"}), 404

    is_fav = db_toggle_fav(video_id)
    return jsonify({"ok": True, "video_id": video_id, "is_favorite": is_fav})


@api.route("/api/fav/list")
def api_fav_list():
    return jsonify({"favorites": sorted(list(db_get_fav_set()))})


@api.route('/delete-file', methods=['POST'])
def delete_file():
    data = request.json
    file_path = data.get("file_path")
    video_id = data.get("video_id")

    if not file_path or not os.path.exists(file_path):
        return jsonify({"error": "File not found"}), 404

    try:
        # delete from filesystem
        os.remove(file_path)

        # optional: mark video as missing in DB
        conn, cur = get_local_db_connection()
        cur = conn.cursor()
        cur.execute("UPDATE videos SET status = 'missing' WHERE video_id = %s", (video_id,))
        conn.commit()
        cur.close(); conn.close()

        return jsonify({"success": True})
    except Exception as e:
        return jsonify({"error": str(e)}), 500
