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 helpers.db_moments import add_moment, list_moments
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 or {}
    file_path = os.path.abspath(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:
        os.remove(file_path)

        conn, cur = get_local_db_connection()
        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

@api.route("/api/moments/<video_id>", methods=["GET"])
def api_list_moments(video_id):
    moments = list_moments(video_id)
    return jsonify(ok=True, moments=moments)

@api.route("/api/moments/<video_id>", methods=["POST"])
def api_add_moment(video_id):
    data = request.get_json(force=True, silent=True) or {}
    try:
        ts = int(data.get("timestamp", 0))
    except (TypeError, ValueError):
        return jsonify(ok=False, error="Invalid timestamp"), 400

    if ts < 0:
        return jsonify(ok=False, error="Negative timestamp"), 400

    new_id = add_moment(video_id, ts)
    return jsonify(ok=True, id=new_id, timestamp=ts)

@api.route("/api/get_recording/", methods=["GET"])
def get_online():
    url = 'http://localhost:8000/get_streamers'
    
    import requests
    r = requests.get(url)
    streamers = r.json()['streamers']
    
    parsed_streamers = []
    for streamer in streamers:
        streamer['is_online'] = streamer['status'] == 'Channel online'
        parsed_streamers.append(streamer)
    
    return jsonify(parsed_streamers)