from flask import Flask, render_template, jsonify, send_from_directory, request
import os

app = Flask(__name__)

# 1) Serve the main page from 'templates/index.html'
@app.route('/')
def index():
    # Renders the HTML/JS that will request the file list and CSV data
    return render_template('index.html')

# 2) Endpoint to list available CSV files in the 'outputs' folder
@app.route('/list-outputs')
def list_outputs():
    outputs_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'outputs/experiments/')
    try:
        # List only files that end with .csv
        files = [f for f in os.listdir(outputs_dir) if f.lower().endswith('.csv')]
    except Exception as e:
        print("Error reading outputs directory:", e)
        files = []
    return jsonify(files)

@app.route('/outputs/<path:filename>')
def serve_outputs(filename):
    return send_from_directory('outputs/experiments/', filename)

@app.route('/api/sign_accuracy')
def sign_accuracy():
    import pandas as pd
    outputs_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'outputs/experiments/')
    # Use the file specified by the user via query param, e.g. ?file=causal_effect_20.csv
    filename = request.args.get("file")
    if not filename:
        return jsonify({"error": "No file specified in query parameter 'file'."}), 400
    csv_file = os.path.join(outputs_dir, filename)
    try:
        df = pd.read_csv(csv_file)
        correct = 0
        incorrect = 0
        for _, row in df.iterrows():
            if pd.isnull(row.get("r_obs")) or pd.isnull(row.get("predicted_coef")):
                continue
            sign_r_obs = 1 if row["r_obs"] >= 0 else -1
            sign_pred = 1 if row["predicted_coef"] >= 0 else -1
            if sign_r_obs == sign_pred:
                correct += 1
            else:
                incorrect += 1
        return jsonify({"correct": correct, "incorrect": incorrect})
    except Exception as e:
        return jsonify({"error": str(e)}), 500

if __name__ == '__main__':
    # By default, Flask serves on http://localhost:5000
    # 'debug=True' automatically reloads on code changes, useful for development
    app.run(debug=True)
