import os
from dotenv import load_dotenv
from flask import Flask, render_template, jsonify, request
import schwabdev

import time

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

app = Flask(__name__)

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



@app.route('/')
def index():
    # Obtenemos la data de alto IV Rank para mostrarla en la plantilla
    return render_template('index.html')

@app.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

@app.route('/get_option_details', methods=['POST'])
def 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]  # Tomar la 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



if __name__ == '__main__':
    app.run(debug=True, port=5003)
