"""Flask app for VibeDB Studio."""

import os
import webbrowser
from threading import Timer


def launch_studio(db, host="127.0.0.1", port=5000):
    """
    Launch VibeDB Studio web interface.

    Args:
        db: VibeDB instance
        host: Host to bind to
        port: Port to run on

    Example:
        >>> db = VibeDB("app.db")
        >>> db.studio(port=5000)
        # Opens http://localhost:5000
    """
    try:
        from flask import Flask, send_from_directory
    except ImportError:
        raise ImportError(
            "Studio requires Flask. Install with: pip install vibedb[studio]"
        )

    app = Flask(__name__, static_folder='static')
    app.db = db  # Attach database to app

    # Register API routes
    from vibedb.studio.api import register_routes
    register_routes(app)

    # Serve static files
    @app.route('/')
    def index():
        """Serve index.html."""
        static_dir = os.path.join(os.path.dirname(__file__), 'static')
        return send_from_directory(static_dir, 'index.html')

    @app.route('/<path:filename>')
    def static_files(filename):
        """Serve static files."""
        static_dir = os.path.join(os.path.dirname(__file__), 'static')
        return send_from_directory(static_dir, filename)

    # Open browser after a short delay
    def open_browser():
        url = f"http://{host if host != '0.0.0.0' else '127.0.0.1'}:{port}"
        print(f"\n🚀 VibeDB Studio running at {url}")
        print(f"📊 Database: {db.path}")
        print(f"📦 Collections: {len(db.collections())}")
        print("\nPress Ctrl+C to stop\n")
        webbrowser.open(url)

    Timer(1.0, open_browser).start()

    # Run Flask app
    app.run(host=host, port=port, debug=False)
