from flask import Blueprint, render_template, request, redirect, url_for, flash
from flask_login import login_required, current_user
from app.extensions import db
from app.models.features import ReportTemplate

templates_bp = Blueprint("templates", __name__, url_prefix="/templates")

SEED_TEMPLATES = [
    {"name": "Restaurant", "name_ar": "مطعم", "sector": "food", "icon": "🍽️",
     "description": "Full-service or fast food restaurant feasibility study",
     "description_ar": "دراسة جدوى مطعم بخدمة كاملة أو وجبات سريعة",
     "default_description": "A restaurant offering [cuisine type] in [city]. Target audience: [demographic]. Estimated capacity: [seats]. Location: [mall/street/standalone].",
     "default_description_ar": "مطعم يقدم [نوع المطبخ] في [المدينة]. الفئة المستهدفة: [الشريحة]. السعة التقديرية: [عدد المقاعد]. الموقع: [مول/شارع/مستقل]."},
    {"name": "E-commerce Store", "name_ar": "متجر إلكتروني", "sector": "ecommerce", "icon": "🛒",
     "description": "Online store selling products via website and mobile app",
     "description_ar": "متجر إلكتروني لبيع المنتجات عبر الموقع والتطبيق",
     "default_description": "An e-commerce platform selling [product category] targeting [market]. Fulfillment: [self/3PL]. Marketing channels: [social/SEO/paid].",
     "default_description_ar": "منصة تجارة إلكترونية لبيع [فئة المنتجات] تستهدف [السوق]. التوصيل: [ذاتي/طرف ثالث]. قنوات التسويق: [اجتماعي/SEO/مدفوع]."},
    {"name": "Tech Startup (SaaS)", "name_ar": "شركة تقنية (SaaS)", "sector": "tech", "icon": "💻",
     "description": "Software as a Service startup feasibility analysis",
     "description_ar": "تحليل جدوى شركة برمجيات كخدمة",
     "default_description": "A SaaS platform that provides [solution] for [target users]. Business model: subscription-based. Key differentiator: [unique feature].",
     "default_description_ar": "منصة SaaS تقدم [الحل] لـ [المستخدمين المستهدفين]. نموذج العمل: اشتراك شهري. الميزة الفريدة: [الميزة]."},
    {"name": "Real Estate", "name_ar": "عقارات", "sector": "realestate", "icon": "🏗️",
     "description": "Real estate development or property management project",
     "description_ar": "مشروع تطوير عقاري أو إدارة ممتلكات",
     "default_description": "A real estate project developing [residential/commercial] properties in [location]. Total units: [number]. Target price range: [range].",
     "default_description_ar": "مشروع عقاري لتطوير [سكني/تجاري] في [الموقع]. عدد الوحدات: [العدد]. النطاق السعري المستهدف: [النطاق]."},
    {"name": "Healthcare Clinic", "name_ar": "عيادة طبية", "sector": "health", "icon": "🏥",
     "description": "Medical clinic or healthcare center feasibility",
     "description_ar": "دراسة جدوى عيادة طبية أو مركز صحي",
     "default_description": "A [specialty] clinic in [city] offering [services]. Target patients: [demographic]. Number of doctors: [number].",
     "default_description_ar": "عيادة [التخصص] في [المدينة] تقدم [الخدمات]. المرضى المستهدفون: [الشريحة]. عدد الأطباء: [العدد]."},
    {"name": "Coffee Shop / Cafe", "name_ar": "مقهى / كافيه", "sector": "food", "icon": "☕",
     "description": "Specialty coffee shop or cafe",
     "description_ar": "مقهى متخصص أو كافيه",
     "default_description": "A specialty coffee shop in [location] targeting [audience]. Concept: [third wave/traditional/themed]. Seating: [number].",
     "default_description_ar": "مقهى متخصص في [الموقع] يستهدف [الفئة]. المفهوم: [الموجة الثالثة/تقليدي/ثيمي]. المقاعد: [العدد]."},
    {"name": "Gym / Fitness Center", "name_ar": "نادي رياضي", "sector": "fitness", "icon": "🏋️",
     "description": "Gym or fitness center feasibility study",
     "description_ar": "دراسة جدوى نادي رياضي أو مركز لياقة",
     "default_description": "A fitness center in [location] offering [services: gym/classes/personal training]. Target: [demographic]. Membership model: [monthly/annual].",
     "default_description_ar": "مركز لياقة في [الموقع] يقدم [خدمات: صالة/حصص/تدريب شخصي]. الفئة المستهدفة: [الشريحة]. نموذج العضوية: [شهري/سنوي]."},
    {"name": "Educational Platform", "name_ar": "منصة تعليمية", "sector": "education", "icon": "📚",
     "description": "Online or hybrid educational platform",
     "description_ar": "منصة تعليمية إلكترونية أو هجينة",
     "default_description": "An educational platform offering [courses/tutoring/certifications] in [subjects]. Target: [students/professionals]. Model: [subscription/per-course].",
     "default_description_ar": "منصة تعليمية تقدم [دورات/تدريس/شهادات] في [المواد]. الفئة: [طلاب/محترفون]. النموذج: [اشتراك/لكل دورة]."},
]


@templates_bp.route("/")
@login_required
def index():
    templates = ReportTemplate.query.filter_by(is_active=True).order_by(ReportTemplate.usage_count.desc()).all()
    if not templates:
        _seed_templates()
        templates = ReportTemplate.query.filter_by(is_active=True).all()
    sectors = list(set(t.sector for t in templates))
    return render_template("templates/index.html", templates=templates, sectors=sectors)


@templates_bp.route("/use/<int:tpl_id>")
@login_required
def use_template(tpl_id):
    tpl = ReportTemplate.query.get_or_404(tpl_id)
    tpl.usage_count += 1
    db.session.commit()
    lang = current_user.language_pref or "ar"
    desc = tpl.default_description_ar if lang == "ar" else tpl.default_description
    return render_template("templates/use.html", template=tpl, default_desc=desc, lang=lang)


def _seed_templates():
    for t in SEED_TEMPLATES:
        tpl = ReportTemplate(**t)
        db.session.add(tpl)
    db.session.commit()
