from flask import Flask, render_template, Response, request
import os, json, urllib.request
from movie import movie_bp

app = Flask(__name__)
app.register_blueprint(movie_bp)

TS_HOST = '127.0.0.1'
TS_PORT = 8090

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/health')
def health():
    return {'status': 'healthy', 'message': 'MovieForCutie is running!'}, 200

@app.route('/torrent/play')
def torrent_play():
    """Proxy TorrServer stream, auto-detecting the video file"""
    hash_val = request.args.get('hash', '')
    file_id = request.args.get('file_id', '0')
    if not hash_val or len(hash_val) < 10:
        return 'Missing or invalid hash', 400
    
    # Check torrent status and find the video file
    try:
        req = urllib.request.Request(f'http://{TS_HOST}:{TS_PORT}/torrents',
            data=json.dumps({"action":"get","hash":hash_val}).encode(),
            headers={'Content-Type':'application/json'})
        r = urllib.request.urlopen(req, timeout=5)
        data = json.loads(r.read())
        if isinstance(data, list):
            data = data[0] if data else {}
        file_stats = data.get('file_stats', [])
        
        if file_stats:
            # Find the largest video file
            video_exts = ('.mp4', '.mkv', '.avi', '.mov', '.webm', '.m4v', '.mpeg', '.mpg', '.ts')
            video_files = [f for f in file_stats if any(f.get('path','').lower().endswith(e) for e in video_exts)]
            if video_files:
                # Use the largest video file
                video_files.sort(key=lambda f: f.get('length', 0), reverse=True)
                file_id = str(video_files[0]['id'])
    except:
        pass
    
    # First add the magnet to TorrServer if not already there
    try:
        magnet = f'magnet:?xt=urn:btih:{hash_val}'
        add_req = urllib.request.Request(f'http://{TS_HOST}:{TS_PORT}/torrents',
            data=json.dumps({"action":"add","link":magnet,"save_to_db":True}).encode(),
            headers={'Content-Type':'application/json'})
        urllib.request.urlopen(add_req, timeout=10)
    except: pass  # May already exist
    
    # Try to stream
    ts_url = f'http://{TS_HOST}:{TS_PORT}/play/{hash_val}/{file_id}'
    try:
        ts_req = urllib.request.Request(ts_url, headers={'User-Agent': 'UltimateStream/1.0'})
        ts_resp = urllib.request.urlopen(ts_req, timeout=30)
        
        def generate():
            while True:
                chunk = ts_resp.read(65536)
                if not chunk: break
                yield chunk
        
        resp_headers = dict(ts_resp.headers)
        return Response(generate(), status=200, headers={
            'Content-Type': resp_headers.get('Content-Type', 'video/mp4'),
            'Content-Length': resp_headers.get('Content-Length', ''),
            'Accept-Ranges': 'bytes',
            'Access-Control-Allow-Origin': '*',
        })
    except urllib.error.HTTPError as he:
        return f'TorrServer error: {he.code}', 502
    except Exception as e:
        return f'Stream error: {e}', 502

@app.route('/api/ts_status')
def ts_status():
    try:
        r = urllib.request.urlopen(f'http://{TS_HOST}:{TS_PORT}/echo', timeout=2)
        alive = bool(r.read())
    except:
        alive = False
    return {'alive': alive}

@app.route('/api/torrent_status')
def torrent_status():
    hash_val = request.args.get('hash', '')
    if not hash_val:
        return {'error': 'no hash'}, 400
    try:
        req = urllib.request.Request(f'http://{TS_HOST}:{TS_PORT}/torrents',
            data=json.dumps({"action":"get","hash":hash_val}).encode(),
            headers={'Content-Type':'application/json'})
        r = urllib.request.urlopen(req, timeout=5)
        data = json.loads(r.read())
        if isinstance(data, list):
            data = data[0] if data else {}
        stat = data.get('stat', 0)
        stat_str = data.get('stat_string', 'Unknown')
        file_count = len(data.get('file_stats', []))
        peers = data.get('total_peers', 0)
        return {'stat': stat, 'stat_string': stat_str, 'files': file_count, 'peers': peers}
    except Exception as e:
        return {'error': str(e)}, 502

if __name__ == "__main__":
    port = int(os.environ.get('PORT', 8800))
    app.run(debug=False, host='0.0.0.0', port=port)
