# ccitm.py
import os
from dotenv import load_dotenv
from flask import Blueprint, render_template, jsonify, request
import schwabdev
import pandas as pd

# Cargar variables de entorno para la API de Schwab
load_dotenv('/var/www/html/backtestingmarket/.env')

ccitm_bp = Blueprint('ccitm', __name__, template_folder='templates')

# Configuración de la API de Schwab
client = schwabdev.Client(
    os.getenv('appKey'),
    os.getenv('appSecret'),
    os.getenv('callbackUrl'),
    verbose=True
)

@ccitm_bp.route('/get_last_price', methods=['POST'])
def get_last_price():
    data = request.get_json()
    ticker = data.get('ticker')
    if not ticker:
        return jsonify({"error": "Ticker no proporcionado"}), 400

    try:
        quote_data = client.quote(ticker).json()
        last_price = quote_data.get(ticker, {}).get('quote', {}).get('lastPrice', "N/A")
        return jsonify({"last_price": last_price}), 200
    except Exception as e:
        print(f"Error al obtener el precio del ticker {ticker}: {e}")
        return jsonify({"error": "Error al obtener el precio"}), 500

@ccitm_bp.route('/get_option_details', methods=['POST'])
def get_option_details():
    print ("Entrando a get_option_details")
    data = request.get_json()
    ticker = data.get('ticker')
    from_date = data.get('date')
    strike_price = str(float(data.get('strike')))  # Convertir el strike a string decimal

    if not ticker or not from_date or not strike_price:
        return jsonify({"error": "Faltan parámetros"}), 400

    try:
        option_data = client.option_chains(ticker, fromDate=from_date, toDate=from_date, strike={strike_price}).json()
        call_exp_date_map = option_data.get("callExpDateMap", {})

        for date_key, strikes in call_exp_date_map.items():
            if strike_price in strikes:
                call_data = strikes[strike_price][0]  # Primera opción encontrada
                if call_data.get("putCall") == "CALL":
                    bid = call_data.get("bid", 0)
                    ask = call_data.get("ask", 0)
                    total_volume = call_data.get("totalVolume", 0)
                    mid_price = (bid + ask) / 2 if bid and ask else "N/A"
                    return jsonify({
                        "bid": bid,
                        "ask": ask,
                        "mid_price": mid_price,
                        "totalVolume": total_volume
                    }), 200

        return jsonify({"error": "No se encontró una opción call con los datos proporcionados"}), 404

    except Exception as e:
        print(f"Error al obtener los detalles de la opción para {ticker}: {e}")
        return jsonify({"error": "Error al obtener los detalles de la opción"}), 500


