from datetime import datetime
from flask import Flask, jsonify, request
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import DateTime, Float, Integer, String
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column

# Create the Flask application
app = Flask(__name__)

@app.route("/")
def index():
    return "<p>MT5 Trade Analytics Backend is running.</p>"


'''
@app.route("/trade", methods=["POST"])
def receive_trade():
    data = request.get_json()

    if not data:
        return jsonify({
            "status": "error",
            "message": "Request body must contain JSON data."
        }), 400

    required_fields = [
        "symbol",
        "position_type",
        "lot_size",
        "entry_price",
        "profit",
        "open_time",
        "close_time"
    ]

    missing_fields = [field for field in required_fields if field not in data]

    if missing_fields:
        return jsonify({
            "status": "error",
            "message": "Missing required fields.",
            "missing_fields": missing_fields
        }), 400

    try:
        open_time = datetime.strptime(data["open_time"], "%Y-%m-%d %H:%M:%S")
        close_time = datetime.strptime(data["close_time"], "%Y-%m-%d %H:%M:%S")

        trade = Trade(
            symbol=data["symbol"],
            order_ticket=data.get("order_ticket"),
            deal_ticket=data.get("deal_ticket"),
            position_ticket=data.get("position_ticket"),
            position_type=data["position_type"],
            position_reason=data.get("position_reason"),
            lot_size=float(data["lot_size"]),
            entry_price=float(data["entry_price"]),
            stop_loss=float(data["stop_loss"]) if data.get("stop_loss") is not None else None,
            take_profit=float(data["take_profit"]) if data.get("take_profit") is not None else None,
            profit=float(data["profit"]),
            open_time=open_time,
            close_time=close_time,
            magic_number=data.get("magic_number")
        )

        db.session.add(trade)
        db.session.commit()

        return jsonify({
            "status": "success",
            "message": "Trade record stored successfully.",
            "trade_id": trade.id
        }), 201

    except ValueError as exc:
        return jsonify({
            "status": "error",
            "message": "Invalid data format.",
            "details": str(exc)
        }), 400

    except Exception as exc:
        db.session.rollback()
        return jsonify({
            "status": "error",
            "message": "An unexpected error occurred while storing the trade.",
            "details": str(exc)
        }), 500

'''