"""
Analytics & Insights — Stories 10.1–10.7.

Routes:
  GET /analytics/               → overview (spending chart + flags)
  GET /analytics/subscriptions  → subscription detector
  GET /analytics/merchants      → merchant spend summary
  GET /analytics/recommendations → history-based budget recommendations
  GET /api/analytics/spending-by-category → JSON for chart
  GET /api/analytics/monthly-totals      → JSON for MoM/YoY chart
"""
from datetime import date

from flask import render_template, request

from app.blueprints.analytics import analytics_bp
from app.models.settings import Settings
from app.services.analytics.trend_analytics import (
    spending_by_category_monthly, monthly_totals, mom_comparison, yoy_comparison
)
from app.services.analytics.budget_analytics import merchant_spend_summary, from_history
from app.services.insights.subscription_detector import detect_subscriptions
from app.services.insights.pattern_flags import get_spending_flags


@analytics_bp.route("/")
def index():
    today = date.today()
    settings = Settings.query.first()
    monthly_income = settings.monthly_income if settings else None

    subscriptions = detect_subscriptions()
    sub_merchants = [s.merchant for s in subscriptions]
    flags = get_spending_flags(monthly_income, sub_merchants)

    mom = mom_comparison(today.year, today.month)
    yoy = yoy_comparison(today.year, today.month)
    monthly = monthly_totals(12)

    return render_template(
        "analytics/index.html",
        flags=flags,
        mom=mom,
        yoy=yoy,
        monthly=monthly,
        today=today,
        active_page="analytics",
    )


@analytics_bp.route("/subscriptions")
def subscriptions():
    subs = detect_subscriptions()
    return render_template(
        "analytics/subscriptions.html",
        subscriptions=subs,
        active_page="analytics",
    )


@analytics_bp.route("/merchants")
def merchants():
    date_from = request.args.get("from")
    date_to = request.args.get("to")
    summary = merchant_spend_summary(limit=20, date_from=date_from, date_to=date_to)
    return render_template(
        "analytics/merchants.html",
        merchants=summary,
        date_from=date_from,
        date_to=date_to,
        active_page="analytics",
    )


@analytics_bp.route("/recommendations")
def recommendations():
    settings = Settings.query.first()
    monthly_income = settings.monthly_income if settings else None

    # Check if enough history exists (≥2 months)
    from sqlalchemy import func
    from app.extensions import db
    from app.models.transaction import Transaction
    month_count = (
        db.session.query(
            func.count(
                func.distinct(
                    func.substr(Transaction.date, 1, 7)
                )
            )
        ).scalar() or 0
    )

    has_history = month_count >= 2
    recs = from_history(monthly_income) if has_history and monthly_income else []

    return render_template(
        "analytics/recommendations.html",
        recommendations=recs,
        has_history=has_history,
        monthly_income=monthly_income,
        active_page="analytics",
    )


