import json
from datetime import date, timedelta
from flask import Blueprint, render_template, request

from src.models import Article

articles_bp = Blueprint("articles", __name__)


@articles_bp.route("/articles")
def index():
    week_filter = request.args.get("week")
    category_filter = request.args.get("category")

    query = Article.query

    if week_filter:
        try:
            year, week_num = week_filter.split("-W")
            week_start = date.fromisocalendar(int(year), int(week_num), 1)
            week_end = week_start + timedelta(days=6)
            query = query.filter(
                Article.pub_date >= str(week_start),
                Article.pub_date < str(week_end + timedelta(days=1)),
            )
        except (ValueError, TypeError):
            pass

    articles = query.order_by(Article.pub_date.desc()).all()

    if category_filter:
        articles = [
            a for a in articles
            if category_filter in json.loads(a.categories)
        ]

    all_categories = set()
    for a in Article.query.all():
        for cat in json.loads(a.categories):
            all_categories.add(cat)

    return render_template(
        "articles.html",
        articles=articles,
        categories=sorted(all_categories),
        week_filter=week_filter or "",
        category_filter=category_filter or "",
    )
