"""Umami analytics sync via REST API.

Uses bearer token auth. Self-hosted instance, no rate limits.
Config already exists: UMAMI_API_URL, UMAMI_API_TOKEN, UMAMI_WEBSITE_ID.
"""

from datetime import timedelta

import httpx

from ..core import config, execute, utcnow, utcnow_iso

_TIMEOUT_SECONDS = 15


async def sync_umami(days_back: int = 3, timeout_seconds: int = _TIMEOUT_SECONDS) -> int:
    """Sync Umami per-URL metrics into seo_analytics_metrics. Returns rows synced."""
    assert 1 <= days_back <= 90, "days_back must be 1-90"
    assert 1 <= timeout_seconds <= 120, "timeout_seconds must be 1-120"

    if not config.UMAMI_API_TOKEN or not config.UMAMI_API_URL:
        return 0  # Umami not configured — skip silently

    started_at = utcnow()

    try:
        rows_synced = 0
        headers = {"Authorization": f"Bearer {config.UMAMI_API_TOKEN}"}
        base = config.UMAMI_API_URL.rstrip("/")
        website_id = config.UMAMI_WEBSITE_ID

        async with httpx.AsyncClient(timeout=timeout_seconds, headers=headers) as client:
            # Fetch per-URL metrics for each day individually
            # (Umami's metrics endpoint returns totals for the period,
            #  so we query one day at a time for daily granularity)
            for day_offset in range(days_back):
                day = utcnow() - timedelta(days=day_offset + 1)
                metric_date = day.strftime("%Y-%m-%d")
                start_ms = int(day.replace(hour=0, minute=0, second=0).timestamp() * 1000)
                end_ms = int(day.replace(hour=23, minute=59, second=59).timestamp() * 1000)

                # Get URL-level metrics
                response = await client.get(
                    f"{base}/api/websites/{website_id}/metrics",
                    params={
                        "startAt": start_ms,
                        "endAt": end_ms,
                        "type": "url",
                        "limit": 500,
                    },
                )
                response.raise_for_status()
                url_metrics = response.json()

                if not isinstance(url_metrics, list):
                    continue

                for entry in url_metrics:
                    page_url = entry.get("x", "")
                    pageviews = entry.get("y", 0)

                    if not page_url:
                        continue

                    await execute(
                        """INSERT OR REPLACE INTO seo_analytics_metrics
                           (metric_date, page_url, pageviews, visitors,
                            bounce_rate, time_avg_seconds)
                           VALUES (?, ?, ?, 0, NULL, NULL)""",
                        (metric_date, page_url, pageviews),
                    )
                    rows_synced += 1

                # Try to get overall stats for bounce rate and visit duration
                # (Umami doesn't provide per-URL bounce rate, only site-wide)
                stats_response = await client.get(
                    f"{base}/api/websites/{website_id}/stats",
                    params={"startAt": start_ms, "endAt": end_ms},
                )
                if stats_response.status_code == 200:
                    stats = stats_response.json()
                    visitors = stats.get("visitors", {}).get("value", 0)
                    bounce_rate = stats.get("bounces", {}).get("value", 0)
                    total_time = stats.get("totaltime", {}).get("value", 0)
                    page_count = stats.get("pageviews", {}).get("value", 1) or 1

                    # Store site-wide stats on the root URL for the day
                    avg_time = int(total_time / max(visitors, 1))
                    br = bounce_rate / max(visitors, 1) if visitors else 0

                    await execute(
                        """INSERT OR REPLACE INTO seo_analytics_metrics
                           (metric_date, page_url, pageviews, visitors,
                            bounce_rate, time_avg_seconds)
                           VALUES (?, '/', ?, ?, ?, ?)""",
                        (metric_date, page_count, visitors, br, avg_time),
                    )

        duration_ms = int((utcnow() - started_at).total_seconds() * 1000)
        await execute(
            """INSERT INTO seo_sync_log
               (source, status, rows_synced, started_at, completed_at, duration_ms)
               VALUES ('umami', 'success', ?, ?, ?, ?)""",
            (rows_synced, started_at.strftime("%Y-%m-%d %H:%M:%S"), utcnow_iso(), duration_ms),
        )
        return rows_synced

    except Exception as exc:
        duration_ms = int((utcnow() - started_at).total_seconds() * 1000)
        await execute(
            """INSERT INTO seo_sync_log
               (source, status, rows_synced, error, started_at, completed_at, duration_ms)
               VALUES ('umami', 'failed', 0, ?, ?, ?, ?)""",
            (str(exc), started_at.strftime("%Y-%m-%d %H:%M:%S"), utcnow_iso(), duration_ms),
        )
        raise
