"""Tools routes — user-facing screener & tool pages (tier-gated).

All routes reuse the same admin templates. Access is controlled by
@tier_required() which checks the user's subscription tier against
the feature's min_tier in the FeatureTierConfig table.
"""
from flask import Blueprint, render_template
from flask_login import login_required
from app.helpers.auth import tier_required
from app.helpers.tier_config import DEFAULT_FEATURES, FEATURE_URL_MAP

tools_bp = Blueprint('tools', __name__, url_prefix='/tools')


@tools_bp.route('/')
@login_required
def tools_home():
    """Tools landing page — grid of ALL features with tier badges."""
    from app.helpers.tier_config import get_all_features, get_tier_pricing
    features = get_all_features()
    pricing = get_tier_pricing()
    return render_template('user/tools_dashboard.html',
                           features=features, pricing=pricing)


@tools_bp.route('/upgrade')
@login_required
def upgrade():
    """Upgrade tier page — pricing cards, QRIS, payment flow."""
    return render_template('upgrade.html')


# ── Programmatically register all feature routes ─────────────────────────────
# Each feature from DEFAULT_FEATURES gets a route at /tools/<url_path>
# decorated with @tier_required(slug) and rendering the admin template.

def _make_view(slug, template):
    """Create a tier-gated view function for a feature."""
    @tier_required(slug)
    def view():
        return render_template(template)
    view.__name__ = f'tool_{slug.replace("-", "_")}'
    return view


for _slug, _url, _template, _tier, _label, _cat, _wave in DEFAULT_FEATURES:
    tools_bp.add_url_rule(_url, endpoint=_slug, view_func=_make_view(_slug, _template))
