import json
from datetime import date, timedelta
from flask import Blueprint, render_template
from flask_login import login_required
from models import Client, Site, DailyMetric, IndexedPage, PSIScore, HealthCheck

dashboard_bp = Blueprint('dashboard', __name__)


def _build_card(site):
    latest_metric = (DailyMetric.query
                      .filter_by(site_id=site.id)
                      .order_by(DailyMetric.date.desc())
                      .first())

    since = date.today() - timedelta(days=8)
    trend = (DailyMetric.query
             .filter(DailyMetric.site_id == site.id, DailyMetric.date >= since)
             .order_by(DailyMetric.date.asc())
             .all())

    not_indexed_count = (IndexedPage.query
                          .filter(IndexedPage.site_id == site.id, IndexedPage.verdict != 'PASS')
                          .count())

    latest_health = (HealthCheck.query
                      .filter_by(site_id=site.id)
                      .order_by(HealthCheck.checked_at.desc())
                      .first())
    health_issues = json.loads(latest_health.issues) if latest_health and latest_health.issues else []

    latest_psi_mobile = (PSIScore.query
                          .filter_by(site_id=site.id, strategy='mobile')
                          .order_by(PSIScore.checked_at.desc())
                          .first())

    return {
        'site': site,
        'metric': latest_metric,
        'trend': [m.sessions for m in trend],
        'not_indexed_count': not_indexed_count,
        'health_issue_count': len(health_issues),
        'health_issues': health_issues[:3],
        'psi': latest_psi_mobile,
    }


@dashboard_bp.route('/')
@login_required
def index():
    clients = Client.query.order_by(Client.name).all()

    groups = []          # one entry per (client, project) with its site cards
    total_sites = 0
    total_not_indexed = 0
    total_health_issues = 0

    for client in clients:
        for project in client.projects:
            active_sites = [s for s in project.sites if s.is_active]
            if not active_sites:
                continue
            cards = [_build_card(s) for s in active_sites]
            groups.append({'client': client, 'project': project, 'cards': cards})
            total_sites += len(cards)
            total_not_indexed += sum(c['not_indexed_count'] for c in cards)
            total_health_issues += sum(c['health_issue_count'] for c in cards)

    unassigned_sites = Site.query.filter_by(project_id=None, is_active=True).order_by(Site.name).all()

    return render_template(
        'dashboard.html',
        groups=groups,
        total_sites=total_sites,
        total_not_indexed=total_not_indexed,
        total_health_issues=total_health_issues,
        unassigned_sites=unassigned_sites,
    )
