from flask import Flask, render_template, jsonify, request
import json
import os
from model_connector import ModelConnector
from dax_parser import DaxParser

app = Flask(__name__)

# Initialize the model connector and DAX parser
model_connector = None
dax_parser = DaxParser()

@app.route('/')
def index():
    """Render the main page."""
    return render_template('index.html')

@app.route('/connect', methods=['POST'])
def connect():
    """Connect to the Analysis Services model."""
    global model_connector
    
    data = request.json
    server = data.get('server')
    database = data.get('database')
    
    try:
        model_connector = ModelConnector(server, database)
        return jsonify({'success': True, 'message': 'Connected successfully'})
    except Exception as e:
        return jsonify({'success': False, 'message': str(e)})

@app.route('/get_measures')
def get_measures():
    """Get all measures from the connected model."""
    if not model_connector:
        return jsonify({'success': False, 'message': 'Not connected to a model'})
    
    try:
        measures = model_connector.get_measures()
        return jsonify({'success': True, 'measures': measures})
    except Exception as e:
        return jsonify({'success': False, 'message': str(e)})

@app.route('/get_call_graph')
def get_call_graph():
    """Generate and return the call graph data."""
    if not model_connector:
        return jsonify({'success': False, 'message': 'Not connected to a model'})
    
    try:
        measures_df = model_connector.get_measures()
        measures = measures_df.to_dict(orient="records")
        graph = dax_parser.build_call_graph(measures)
        return jsonify({'success': True, 'graph': graph})
    except Exception as e:
        return jsonify({'success': False, 'message': str(e)})

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