import os
import uuid
import re
import logging
import subprocess
from flask import Flask, render_template, request, send_from_directory, jsonify

# =========================
# APP CONFIG
# =========================
app = Flask(__name__)

BASE_DIR = os.path.dirname(os.path.abspath(__file__))
DOWNLOAD_DIR = os.path.join(BASE_DIR, "downloads")

os.makedirs(DOWNLOAD_DIR, exist_ok=True)

# =========================
# LOGGING
# =========================
logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s - %(levelname)s - %(message)s"
)

# =========================
# UTILS
# =========================
def clean_text(text: str) -> str:
    text = re.sub(r"<[^>]+>", "", text)
    text = re.sub(r"\s+", " ", text)
    return text.strip()

def run_cmd(cmd: list) -> bool:
    try:
        subprocess.run(cmd, check=True)
        return True
    except Exception as e:
        logging.error(f"Command failed: {e}")
        return False

def download_audio(url: str, output_path: str) -> bool:
    cmd = [
        "yt-dlp",
        "-f", "bestaudio",
        "-x",
        "--audio-format", "mp3",
        "-o", output_path,
        url
    ]
    return run_cmd(cmd)

def download_subtitles(url: str, folder: str) -> bool:
    cmd = [
        "yt-dlp",
        "--write-auto-subs",
        "--write-subs",
        "--all-subs",
        "--sub-format", "srt",
        "--skip-download",
        "-o", f"{folder}/%(title)s.%(ext)s",
        url
    ]
    return run_cmd(cmd)

def find_file(folder: str, ext: str):
    for file in os.listdir(folder):
        if file.endswith(ext):
            return os.path.join(folder, file)
    return None

def parse_srt(file_path: str) -> str:
    text = ""
    with open(file_path, "r", encoding="utf-8") as f:
        for line in f:
            line = line.strip()
            if "-->" in line or line.isdigit():
                continue
            line = clean_text(line)
            if line:
                text += line + "\n"
    return text

# =========================
# CORE PIPELINE (NO AI)
# =========================
def process_video(url: str, folder: str):

    logging.info(f"Processing: {url}")

    # STEP 1: subtitles only
    success = download_subtitles(url, folder)

    if success:
        srt_file = find_file(folder, ".srt")

        if srt_file:
            logging.info("Subtitle found!")
            text = parse_srt(srt_file)
            return text, "subtitle"

    # STEP 2: fallback = audio only (NO WHISPER)
    logging.info("No subtitles found. Returning audio download only.")

    audio_path = os.path.join(folder, "audio.mp3")

    audio_success = download_audio(url, audio_path)

    if not audio_success:
        return "", "failed"

    return "Audio downloaded successfully (no transcription on this server)", "audio_only"

# =========================
# ROUTES
# =========================
@app.route("/", methods=["GET"])
def index():
    return render_template("index.html")

@app.route("/convert", methods=["POST"])
def convert():
    url = request.form.get("url")

    if not url:
        return jsonify({"error": "No URL provided"}), 400

    folder_id = str(uuid.uuid4())
    folder_path = os.path.join(DOWNLOAD_DIR, folder_id)
    os.makedirs(folder_path, exist_ok=True)

    text, mode = process_video(url, folder_path)

    output_file = os.path.join(folder_path, "output.txt")

    with open(output_file, "w", encoding="utf-8") as f:
        f.write(text)

    return jsonify({
        "status": "success",
        "mode": mode,
        "file": f"/download/{folder_id}/output.txt"
    })

@app.route("/download/<folder>/<filename>")
def download(folder, filename):
    path = os.path.join(DOWNLOAD_DIR, folder)
    return send_from_directory(path, filename, as_attachment=True)

@app.route("/health")
def health():
    return {"status": "running"}

# =========================
# RUN
# =========================
if __name__ == "__main__":
    print("🚀 Server starting...")
    app.run(host="0.0.0.0", port=5000, debug=True)