from flask import Blueprint, render_template, request, redirect, url_for, flash, jsonify
from flask_login import login_required, current_user
from app.extensions import db, csrf
from app.models.features import Grant
from app.models.report import Report
from functools import wraps

grants_bp = Blueprint("grants", __name__, url_prefix="/grants")


def premium_required(f):
    """Decorator to require premium subscription for route access."""
    @wraps(f)
    @login_required
    def decorated(*args, **kwargs):
        if not current_user.has_premium_access:
            flash("هذه الميزة متاحة فقط للمشتركين في الخطط المدفوعة", "warning")
            return redirect(url_for('subscription.plans'))
        return f(*args, **kwargs)
    return decorated

SEED_GRANTS = [
    {"name": "Monsha'at SME Financing", "name_ar": "تمويل منشآت للمنشآت الصغيرة والمتوسطة", "provider": "Monsha'at (منشآت)", "country": "SA", "sector": "all", "max_amount": 5000000, "currency": "SAR", "url": "https://www.monshaat.gov.sa", "description": "Financing and support programs for Saudi SMEs including Kafalah guarantee program"},
    {"name": "Saudi Development Fund (SDB)", "name_ar": "بنك التنمية الاجتماعية", "provider": "Social Development Bank", "country": "SA", "sector": "all", "max_amount": 500000, "currency": "SAR", "url": "https://www.sdb.gov.sa", "description": "Soft loans for Saudi entrepreneurs and micro-enterprises"},
    {"name": "Tamkeen Bahrain", "name_ar": "تمكين البحرين", "provider": "Tamkeen", "country": "BH", "sector": "all", "max_amount": 100000, "currency": "BHD", "url": "https://www.tamkeen.bh", "description": "Enterprise support and development fund for Bahrain businesses"},
    {"name": "Khalifa Fund (UAE)", "name_ar": "صندوق خليفة (الإمارات)", "provider": "Khalifa Fund", "country": "AE", "sector": "all", "max_amount": 3000000, "currency": "AED", "url": "https://www.khalifafund.gov.ae", "description": "SME development fund for UAE nationals"},
    {"name": "KAUST Innovation Fund", "name_ar": "صندوق ابتكار كاوست", "provider": "KAUST", "country": "SA", "sector": "tech", "max_amount": 2000000, "currency": "SAR", "url": "https://innovation.kaust.edu.sa", "description": "Deep tech and research-based startup funding"},
    {"name": "Saudi Venture Capital (SVC)", "name_ar": "الشركة السعودية للاستثمار الجريء", "provider": "SVC", "country": "SA", "sector": "tech", "max_amount": 10000000, "currency": "SAR", "url": "https://www.svc.com.sa", "description": "Venture capital investment in Saudi tech startups via fund-of-funds model"},
    {"name": "Wa'ed by Aramco", "name_ar": "واعد من أرامكو", "provider": "Saudi Aramco", "country": "SA", "sector": "energy,tech", "max_amount": 5000000, "currency": "SAR", "url": "https://www.waed.net", "description": "Entrepreneurship program by Saudi Aramco for tech and energy startups"},
    {"name": "MCIT Digital Fund", "name_ar": "صندوق الاتصالات الرقمي", "provider": "MCIT", "country": "SA", "sector": "tech", "max_amount": 1000000, "currency": "SAR", "url": "https://www.mcit.gov.sa", "description": "Digital transformation and tech startup support by Ministry of Communications"},
]


@grants_bp.route("/")
@premium_required
def index():
    grants = Grant.query.filter_by(is_active=True).all()
    if not grants:
        _seed_grants()
        grants = Grant.query.filter_by(is_active=True).all()
    country = request.args.get("country", "").strip()
    if country:
        grants = [g for g in grants if g.country == country]
    countries = list(set(g.country for g in Grant.query.filter_by(is_active=True).all()))
    return render_template("grants/index.html", grants=grants, countries=countries, current_country=country)


@grants_bp.route("/match/<int:report_id>")
@login_required
def match(report_id):
    report = Report.query.get_or_404(report_id)
    if report.user_id != current_user.id:
        flash("Access denied.", "error")
        return redirect(url_for("grants.index"))
    try:
        from app.ai.diamond import call_ai, run_sync
        grants_list = "\n".join([f"- {g.name}: {g.description} (max {g.max_amount} {g.currency})" for g in Grant.query.filter_by(is_active=True).all()])
        prompt = f"""Given this project: "{report.project_name}" — {report.project_description}
And these available grants/funds:
{grants_list}

Rank the top 5 most relevant grants for this project. For each, explain WHY it's a good fit and give a match score (0-100).
Return as JSON array: [{{"name": "...", "score": 85, "reason": "..."}}]
Language: {"Arabic" if report.language == "ar" else "English"}"""
        messages = [{"role": "system", "content": "Return only valid JSON array."}, {"role": "user", "content": prompt}]
        result = run_sync(call_ai(messages, model_type="fast"))
        import json
        try:
            matches = json.loads(result)
        except Exception:
            matches = []
    except Exception:
        matches = []
    return render_template("grants/match.html", report=report, matches=matches)


def _seed_grants():
    for g in SEED_GRANTS:
        db.session.add(Grant(**g))
    db.session.commit()
