from datetime import date, timedelta
from flask import Blueprint, render_template, redirect, url_for, flash

from app import db
from src.models import Article, Issue

dashboard_bp = Blueprint("dashboard", __name__)


@dashboard_bp.route("/")
def index():
    today = date.today()
    week_start = today - timedelta(days=today.weekday())
    week_end = week_start + timedelta(days=6)

    articles_this_week = Article.query.filter(
        Article.pub_date >= str(week_start),
        Article.pub_date < str(week_end + timedelta(days=1)),
    ).count()

    total_articles = Article.query.count()
    total_issues = Issue.query.count()
    latest_issue = Issue.query.order_by(Issue.created_at.desc()).first()

    from flask import current_app
    scheduler_mgr = current_app.config.get("SCHEDULER_MANAGER")
    scheduler_status = scheduler_mgr.get_status() if scheduler_mgr else {"running": False}

    return render_template(
        "dashboard.html",
        articles_this_week=articles_this_week,
        total_articles=total_articles,
        total_issues=total_issues,
        latest_issue=latest_issue,
        scheduler_status=scheduler_status,
    )


@dashboard_bp.route("/fetch-now", methods=["POST"])
def fetch_now():
    from src.fetcher import fetch_and_cache_articles
    result = fetch_and_cache_articles()
    if result.get("error"):
        flash(f"Fetch error: {result['error']}", "error")
    else:
        flash(f"Fetched {result['new']} new articles, {result['skipped']} skipped.")
    return redirect(url_for("dashboard.index"))
