import matplotlib
matplotlib.use("Agg")  # Use non-interactive backend
import matplotlib.pyplot as plt
from flask import Flask, request, jsonify
import pandas as pd
import json
import logging
import datetime

app = Flask(__name__)
logging.basicConfig(level=logging.DEBUG)

def generate_commentary(corr, rolling_series):
    """Generate a commentary based on overall and recent correlation values."""
    commentary = ""
    if corr >= 0.8:
        commentary += ("The currency pairs have a very strong positive correlation, meaning "
                       "they typically move together. This may support the use of hedging strategies.\n")
    elif corr >= 0.5:
        commentary += ("The pairs display a moderately strong positive correlation with some deviations, "
                       "indicating they often move in the same direction.\n")
    elif corr >= 0.0:
        commentary += ("The overall correlation is weakly positive, suggesting occasional movement together "
                       "but limited consistency, which may offer diversification opportunities.\n")
    elif corr >= -0.5:
        commentary += ("The pairs exhibit a weak to moderate negative correlation; they tend to move in opposite "
                       "directions, which can be useful for diversification.\n")
    else:
        commentary += ("The pairs have a strong negative correlation, implying they generally move in opposite "
                       "directions, a factor exploitable in hedging strategies.\n")
    
    if not rolling_series.empty:
        recent_trend = rolling_series.iloc[-1]
        commentary += f"Recently, the rolling correlation is at {recent_trend:.2f}. "
        if recent_trend > 0.8:
            commentary += ("This high correlation suggests near mirror-like movement. "
                           "Relative strength approaches may need reconsideration for diversification.")
        elif recent_trend < 0.3:
            commentary += ("A significant drop in correlation indicates potential decoupling. "
                           "This may signal opportunities in pair divergence trades.")
        else:
            commentary += ("The correlation remains moderate, meaning the pairs show some synchronization but also "
                           "retain independent movement.")
    return commentary

@app.route('/analyze', methods=['POST'])
def analyze():
    data = request.get_json(silent=True)
    if not data:
        raw_data = request.data.decode('utf-8').strip()
        app.logger.debug("Raw request data: %s", raw_data)
        try:
            end_index = raw_data.rfind("}")
            trimmed_data = raw_data[:end_index+1] if end_index != -1 else raw_data
            data = json.loads(trimmed_data)
        except Exception as e:
            app.logger.error("Failed to parse JSON: %s", str(e))
            return jsonify({"error": "Invalid JSON received"}), 400

    try:
        symbol1 = data["symbol1"]
        symbol2 = data["symbol2"]
        
        data1 = pd.DataFrame(data["data1"])
        data2 = pd.DataFrame(data["data2"])
        
        data1['Time'] = pd.to_datetime(data1['time'])
        data2['Time'] = pd.to_datetime(data2['time'])
        
        merged = pd.merge(data1, data2, on="Time", suffixes=('_' + symbol1, '_' + symbol2))
        
        correlation = merged[f'close_{symbol1}'].corr(merged[f'close_{symbol2}'])
        merged['RollingCorrelation'] = merged[f'close_{symbol1}'].rolling(window=50).corr(merged[f'close_{symbol2}'])
        
        plt.figure(figsize=(7.5, 6), dpi=100)
        plt.plot(merged['Time'], merged['RollingCorrelation'], label="Rolling Correlation (50 bars)")
        plt.xlabel("Time")
        plt.ylabel("Correlation")
        plt.title(f"{symbol1} and {symbol2} Rolling Correlation")
        plt.legend()
        plt.grid(True)
        plt.tight_layout()
        plot_filename = "rolling_correlation.png"
        plt.savefig(plot_filename)
        plt.close()
        
        commentary = generate_commentary(correlation, merged['RollingCorrelation'])
        
        response = {
            "correlation": correlation,
            "commentary": commentary,
            "message": f"Plot saved as {plot_filename}"
        }
        return jsonify(response)
    except Exception as e:
        app.logger.error("Error in processing: %s", str(e))
        return jsonify({"error": str(e)}), 500

if __name__ == "__main__":
    app.run(host="127.0.0.1", port=5000)
