import os
from flask import Flask, request, jsonify, render_template
from dotenv import load_dotenv
import stripe
import json
from datetime import datetime

load_dotenv()

app = Flask(__name__)

stripe.api_key = os.getenv("STRIPE_SECRET_KEY")
PUBLISHABLE_KEY = os.getenv("STRIPE_PUBLISHABLE_KEY")
DEFAULT_CURRENCY = os.getenv("DEFAULT_CURRENCY", "GBP")

# In-memory supporter storage (in production, use a proper database)
supporters = []

@app.route("/")
def index():
    return render_template("index.html")

@app.route("/config")
def config():
    return jsonify({"publishableKey": PUBLISHABLE_KEY})

@app.route("/create-payment-intent", methods=["POST"])
def create_payment():
    data = request.get_json()
    amount = int(float(data["amount"]) * 100)  # convert to cents/pence
    currency = data.get("currency", DEFAULT_CURRENCY).lower()
    supporter_name = data.get("supporterName", "").strip()

    intent = stripe.PaymentIntent.create(
        amount=amount,
        currency=currency,
        automatic_payment_methods={
            "enabled": True,
            "allow_redirects": "never"  # Keep users on the page
        },
        metadata={
            "source": "donation_page",
            "currency": currency,
            "supporter_name": supporter_name if supporter_name else "Anonymous"
        }
    )
    return jsonify({"clientSecret": intent.client_secret})

@app.route("/add-supporter", methods=["POST"])
def add_supporter():
    data = request.get_json()
    supporter_name = data.get("name", "Anonymous").strip()
    amount = data.get("amount", 0)
    currency = data.get("currency", DEFAULT_CURRENCY)
    
    if supporter_name and supporter_name != "Anonymous":
        # Limit name length and sanitize
        supporter_name = supporter_name[:30]
        
        supporter = {
            "name": supporter_name,
            "amount": amount,
            "currency": currency,
            "timestamp": datetime.now().isoformat(),
            "time_ago": "just now"
        }
        
        # Add to beginning of list and keep only last 50
        supporters.insert(0, supporter)
        supporters[:] = supporters[:50]
        
        return jsonify({"success": True})
    
    return jsonify({"success": False})

@app.route("/supporters", methods=["GET"])
def get_supporters():
    # Update time_ago for each supporter
    now = datetime.now()
    for supporter in supporters:
        try:
            timestamp = datetime.fromisoformat(supporter["timestamp"])
            diff = now - timestamp
            
            if diff.days > 0:
                supporter["time_ago"] = f"{diff.days}d ago"
            elif diff.seconds > 3600:
                hours = diff.seconds // 3600
                supporter["time_ago"] = f"{hours}h ago"
            elif diff.seconds > 60:
                minutes = diff.seconds // 60
                supporter["time_ago"] = f"{minutes}m ago"
            else:
                supporter["time_ago"] = "just now"
        except:
            supporter["time_ago"] = "recently"
    
    return jsonify({"supporters": supporters[:20]})  # Return last 20

if __name__ == "__main__":
    app.run(port=4242, debug=True)
