"""REST API for VibeDB Studio."""

from flask import jsonify, request
import json


def register_routes(app):
    """
    Register API routes with Flask app.

    Args:
        app: Flask application instance
    """

    @app.route('/api/stats', methods=['GET'])
    def get_stats():
        """Get database statistics."""
        try:
            stats = app.db.stats()
            return jsonify(stats)
        except Exception as e:
            return jsonify({'error': str(e)}), 500

    @app.route('/api/collections', methods=['GET'])
    def list_collections():
        """List all collections."""
        try:
            collections = app.db.collections()
            result = []
            for name in collections:
                coll = app.db.collection(name)
                result.append({
                    'name': name,
                    'document_count': coll.count()
                })
            return jsonify(result)
        except Exception as e:
            return jsonify({'error': str(e)}), 500

    @app.route('/api/collections/<name>/docs', methods=['GET'])
    def list_documents(name):
        """List documents in a collection with pagination."""
        try:
            coll = app.db.collection(name)

            # Pagination parameters
            limit = int(request.args.get('limit', 50))
            skip = int(request.args.get('skip', 0))

            # Get documents
            cursor = coll.find().skip(skip).limit(limit)
            docs = [doc.to_dict() for doc in cursor]

            # Get total count
            total = coll.count()

            return jsonify({
                'documents': docs,
                'total': total,
                'skip': skip,
                'limit': limit
            })
        except Exception as e:
            return jsonify({'error': str(e)}), 500

    @app.route('/api/collections/<name>/docs/<doc_id>', methods=['GET'])
    def get_document(name, doc_id):
        """Get a single document."""
        try:
            coll = app.db.collection(name)
            doc = coll.get(doc_id)

            if doc:
                return jsonify(doc.to_dict())
            else:
                return jsonify({'error': 'Document not found'}), 404
        except Exception as e:
            return jsonify({'error': str(e)}), 500

    @app.route('/api/collections/<name>/query', methods=['POST'])
    def execute_query(name):
        """Execute a query on a collection."""
        try:
            coll = app.db.collection(name)
            data = request.get_json()

            query = data.get('query', {})
            limit = data.get('limit', 50)
            skip = data.get('skip', 0)
            sort_field = data.get('sort_field')
            sort_dir = data.get('sort_dir', 1)

            # Execute query
            cursor = coll.find(query).skip(skip).limit(limit)

            if sort_field:
                cursor = cursor.sort(sort_field, sort_dir)

            docs = [doc.to_dict() for doc in cursor]

            return jsonify({
                'documents': docs,
                'count': len(docs)
            })
        except Exception as e:
            return jsonify({'error': str(e)}), 500

    @app.route('/api/collections/<name>/indexes', methods=['GET'])
    def list_indexes(name):
        """List indexes for a collection."""
        try:
            coll = app.db.collection(name)
            indexes = coll.list_indexes()
            return jsonify(indexes)
        except Exception as e:
            return jsonify({'error': str(e)}), 500

    @app.route('/api/collections/<name>/indexes', methods=['POST'])
    def create_index(name):
        """Create an index."""
        try:
            coll = app.db.collection(name)
            data = request.get_json()

            fields = data.get('fields', [])
            unique = data.get('unique', False)

            index_id = coll.create_index(fields, unique=unique)

            return jsonify({
                'index_id': index_id,
                'message': 'Index created successfully'
            })
        except Exception as e:
            return jsonify({'error': str(e)}), 500

    @app.route('/api/collections/<name>/indexes/<index_name>', methods=['DELETE'])
    def drop_index(name, index_name):
        """Drop an index."""
        try:
            coll = app.db.collection(name)
            success = coll.drop_index(index_name)

            if success:
                return jsonify({'message': 'Index dropped successfully'})
            else:
                return jsonify({'error': 'Index not found'}), 404
        except Exception as e:
            return jsonify({'error': str(e)}), 500

    @app.route('/api/collections/<name>/suggestions', methods=['GET'])
    def get_index_suggestions(name):
        """Get index suggestions for a collection."""
        try:
            coll = app.db.collection(name)
            suggestions = coll.index_suggestions()
            return jsonify(suggestions)
        except Exception as e:
            return jsonify({'error': str(e)}), 500

    @app.route('/api/slow-queries', methods=['GET'])
    def list_slow_queries():
        """List slow queries across all collections."""
        try:
            # Get slow queries from database
            sql = """
                SELECT collection, query, execution_time_ms, timestamp
                FROM _vibedb_slow_queries
                ORDER BY timestamp DESC
                LIMIT 100
            """
            rows = app.db.engine.execute(sql, fetch='all')

            queries = []
            for row in rows:
                queries.append({
                    'collection': row['collection'],
                    'query': json.loads(row['query']),
                    'execution_time_ms': row['execution_time_ms'],
                    'timestamp': row['timestamp']
                })

            return jsonify(queries)
        except Exception as e:
            return jsonify({'error': str(e)}), 500
