"""
Scheduled daily data pull for every active site.

cPanel cron command (adjust paths to your actual username/app path):

    /home/CPANELUSER/virtualenv/seo_dashboard/3.11/bin/python \
        /home/CPANELUSER/seo_dashboard/cron/fetch_daily_metrics.py \
        >> /home/CPANELUSER/seo_dashboard/cron/fetch.log 2>&1

Suggested schedule: once daily, e.g. 6:00 AM server time
(GA4/GSC data for "yesterday" is reliably available by then).
"""
import os
import sys
from datetime import datetime

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from app import create_app
from models import Site

app = create_app()

with app.app_context():
    from services.fetch_orchestrator import run_site_check, sync_gsc_site_list

    new_count = sync_gsc_site_list(app.config)
    if new_count:
        print(f"[{datetime.now()}] Discovered {new_count} new site(s) from Search Console")

    sites = Site.query.filter_by(is_active=True).all()
    print(f"[{datetime.now()}] Starting daily fetch for {len(sites)} site(s)")

    for site in sites:
        print(f"  -> {site.name} ({site.url})")
        try:
            results = run_site_check(site, app.config)
            for r in results:
                print(f"     {r}")
        except Exception as e:
            print(f"     UNHANDLED ERROR: {e}")

    print(f"[{datetime.now()}] Daily fetch complete")
