"""Route for Flask to access database and make query
Will be protected by api
Also will use prepared statments
"""

import sqlite3

from flask import Blueprint, request, current_app, jsonify

from src.in_io import sqlite as pysql
from src.http.auth import verify_api_key

dataget_bp = Blueprint("dataget", __name__)


def register_dataget(app, route_name):
    """Route to register the data_get route

    Parameters
    ----------
    app : _type_
        _description_
    route_name : _type_
        _description_

    Returns
    -------
    _type_
        _description_
    """
    if not route_name.startswith("/"):
        route_name = "/" + route_name

    get_route = route_name + "/get"  # e.g. /datalog/get

    def handle_get():
        auth = verify_api_key()
        if auth:
            return auth

        if "sqlite" not in current_app.handler.save_dict:
            return jsonify({"error": "No database configured"}), 409

        inator = request.args.get("inator")
        if not inator:
            return jsonify({"error": "Missing 'inator' parameter"}), 400

        db_path = current_app.handler.save_dict["sqlite"]["db_path"]
        __, connection, cursor = pysql.connect_db(db_path, 0)

        tab_known, dev_inf = pysql.get_device_info(cursor, inator)
        if not tab_known:
            connection.close()
            return jsonify({"error": f"Inator '{inator}' not found"}), 404

        # Matches the naming convention in create_dev_log_table
        table = f"{dev_inf['id']}_{dev_inf['device_name']}"

        reserved = {"inator"}
        filters = {k: v for k, v in request.args.items() if k not in reserved}

        try:
            if filters:
                valid_columns = {
                    row[1]
                    for row in cursor.execute(
                        f"PRAGMA table_info('{table}')"
                    ).fetchall()
                }
                invalid = [col for col in filters if col not in valid_columns]
                if invalid:
                    connection.close()
                    return jsonify({"error": f"Invalid columns: {invalid}"}), 400

                where_clause = " AND ".join([f"{col} = ?" for col in filters])
                values = list(filters.values())
                cursor.execute(f"SELECT * FROM '{table}' WHERE {where_clause}", values)
            else:
                cursor.execute(f"SELECT * FROM '{table}'")

            rows = cursor.fetchall()
            columns = [desc[0] for desc in cursor.description]
            results = [dict(zip(columns, row)) for row in rows]

        except sqlite3.Error as e:
            return jsonify({"error": f"Query failed: {str(e)}"}), 400
        finally:
            connection.close()

        return jsonify({"data": results, "count": len(results)}), 200

    app.add_url_rule(
        get_route, endpoint="handle_get", view_func=handle_get, methods=["GET"]
    )
