from flask import Blueprint, jsonify, request
# Import the new function
from .backend_utilities import (
    get_primary_id_name, 
    get_id_list, 
    get_id_occurrences, 
    get_keys, 
    get_secondary_id_name, 
    get_extra_cols,
    get_cell_value_change,
    get_reconciliation_type  # Added import
)
import json

fetch_api = Blueprint("fetch_api", __name__, url_prefix="/api")

@fetch_api.route("/hello", methods=["GET"])
def hello():
    return jsonify({"key": "hello"})

@fetch_api.route("/primary_id_name", methods=["GET"])
def primary_id_name():
    primary_id_name = get_primary_id_name()
    print(primary_id_name)
    return json.dumps(primary_id_name)

@fetch_api.route("/secondary_id_name", methods=["GET"])
def secondary_id_name():
    secondary_id_name = get_secondary_id_name()
    print(secondary_id_name)
    return json.dumps(secondary_id_name)


@fetch_api.route("/id_list", methods=["GET"])
def id_list():
    id_list = get_id_list()
    print(id_list)
    return jsonify(id_list)

@fetch_api.route("/id_occurrences", methods=["GET"])
def id_occurrences():
    id_occurrences = get_id_occurrences()
    print(id_occurrences)
    return jsonify({"id_occurrences": id_occurrences})  # Wrap in a dictionary

@fetch_api.route("/keys_info", methods=["GET"])
def keys_info():
    keys = get_keys()
    print(keys)
    return json.dumps(keys)

# Add the new endpoint for reconciliation_type
@fetch_api.route("/reconciliation_type", methods=["GET"])
def reconciliation_type():
    reco_type = get_reconciliation_type()
    print(reco_type)
    return json.dumps(reco_type)

@fetch_api.route("/save_selected_id/<selected_id>", methods=["GET"])
def save_selected_id(selected_id:str):
    if selected_id is None:
        return jsonify({"error": "No ID provided"}), 400
    print(f"Received selected_id: {selected_id}")
    return jsonify({"message": f"Selected ID {selected_id} received successfully."}), 200

@fetch_api.route("/extra_cols", methods=["GET"])
def extra_cols():
    extra_cols = get_extra_cols()
    print(extra_cols)
    return json.dumps(extra_cols)

@fetch_api.route("/cell_value_change", methods=["POST"])
def cell_value_change():
    payload = request.get_json(force=True)
    headers = dict(request.headers)
    resp = get_cell_value_change(payload, headers)
    return jsonify(resp)