import json
import re
import os
from flask import Flask, request, jsonify
from flask_cors import CORS  # we'll implement CORS manually if not available
import yt_dlp

app = Flask(__name__)

# CORS – allow requests from anywhere
@app.after_request
def after_request(response):
    response.headers.add('Access-Control-Allow-Origin', '*')
    response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization')
    response.headers.add('Access-Control-Allow-Methods', 'GET,OPTIONS')
    return response

# Optional: simple in-memory cache (dictionary) – you can expand this later
video_cache = {}

def is_valid_id(video_id):
    return bool(re.match(r'^[a-zA-Z0-9_-]{11}$', video_id))

def extract_info(video_id):
    """Use yt-dlp to fetch metadata, return dict with title and formats."""
    url = f'https://www.youtube.com/watch?v={video_id}'
    ydl_opts = {
        'quiet': True,
        'no_warnings': True,
        'extract_flat': False,  # we need full format list
        'skip_download': True,
        'force_generic_extractor': False,
        'youtube_include_dash_manifest': False,  # avoid huge manifest
        'format': 'bestvideo+bestaudio/best',  # we'll extract all anyway
    }
    with yt_dlp.YoutubeDL(ydl_opts) as ydl:
        info = ydl.extract_info(url, download=False)
        # yt-dlp returns a complex dict; we simplify it
        title = info.get('title', 'video')
        formats = info.get('formats', [])
        simplified_formats = []
        for f in formats:
            # extract only what we need
            fmt = {
                'format_id': f.get('format_id'),
                'ext': f.get('ext'),
                'url': f.get('url'),
                'acodec': f.get('acodec') or 'none',
                'vcodec': f.get('vcodec') or 'none',
                'filesize': f.get('filesize') or f.get('filesize_approx'),
                'format_note': f.get('format_note', ''),
            }
            simplified_formats.append(fmt)
        return {
            'title': title,
            'formats': simplified_formats,
            'id': video_id,
        }

@app.route('/api/info')
def api_info():
    video_id = request.args.get('id', '')
    if not video_id:
        return jsonify({'ok': False, 'message': 'Missing id parameter'}), 400
    if not is_valid_id(video_id):
        return jsonify({'ok': False, 'message': 'Invalid video ID'}), 400

    # Check cache
    if video_id in video_cache:
        return jsonify({'ok': True, **video_cache[video_id]})

    try:
        data = extract_info(video_id)
    except Exception as e:
        return jsonify({'ok': False, 'message': str(e)}), 502

    # Cache for 1 hour (in seconds)
    video_cache[video_id] = data
    # Simple cache expiration: you could add a timestamp
    return jsonify({'ok': True, **data})

@app.route('/health')
def health():
    return 'OK', 200

# If running directly (for local testing)
if __name__ == '__main__':
    port = int(os.environ.get('PORT', 5000))
    app.run(host='0.0.0.0', port=port, debug=False)