"""Functions to log data via http POST"""

import datetime
from flask import Blueprint, request, current_app

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

datalog_bp = Blueprint("datalog", __name__)


def register_datalog(app, route_name):
    if not route_name.startswith("/"):
        route_name = "/" + route_name

    def handle_post():
        """function to handle the POST request for logging"""
        auth = verify_api_key()
        if auth:
            return auth

        handler = current_app.handler
        request_data = request.get_json(silent=True)
        if not request_data:
            return {"error": "Invalid or missing JSON"}, 400

        ct = datetime.datetime.now()
        ctdata = {"timestamp": int(ct.timestamp()), **request_data}

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

            if "inator" not in ctdata:
                return {"error": "Missing 'inator' field"}, 400

            tab_known, dev_inf = pysql.get_device_info(cursor, ctdata["inator"])
            if tab_known:
                del ctdata["inator"]
                key_dict = pysql.get_data_id_key(cursor, dev_inf, ctdata)
                pysql.insert_dev_log_table(cursor, dev_inf, ctdata, key_dict)
                connection.commit()
                connection.close()

        if "file" in handler.save_dict:
            filepath = handler.save_dict["file"]["filepath"]
            inio.save_plain_text(filepath, ct, request_data)

        if not any(k in handler.save_dict for k in ("sqlite", "file")):
            return {
                "message": "Data received, but no logging set up",
                "data": ctdata,
            }, 418
        else:
            return {"message": "Data received", "data": ctdata}, 200

    # Register directly on the app instead of via blueprint decorator
    app.add_url_rule(
        route_name, endpoint="handle_post", view_func=handle_post, methods=["POST"]
    )
