from flask import Flask, render_template, request, jsonify, Response
import requests
from fastapi_app import fastapi_app
from werkzeug.middleware.dispatcher import DispatcherMiddleware
from werkzeug.serving import run_simple

# Initialize Flask app
flask_app = Flask(__name__)

# Create a simple Flask route
@flask_app.route('/')
def flask_hello():
    return render_template('index.html', message="Hello from Flask!")

def hello_from_fastapi():
    # Make an HTTP request to the FastAPI route
    response = requests.get('http://localhost:7860/fastapi')
    if response.status_code == 200:
        return response.json()
    else:
        return {"error": "Failed to fetch from FastAPI"}

# Create a new Flask route to use the hello_from_fastapi function
@flask_app.route('/fetch-from-fastapi')
def fetch_from_fastapi():
    result = hello_from_fastapi()
    return render_template('index.html', message=result)

# Combine Flask and FastAPI using DispatcherMiddleware
application = DispatcherMiddleware(flask_app, {
    '/fastapi': fastapi_app
})

if __name__ == '__main__':
    run_simple('0.0.0.0', 7860, application)