Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

135 KB
Raw Blame
"""Routes for metrics dashboard."""

import asyncio

from fastapi import APIRouter, Depends, Request
from fastapi.responses import JSONResponse
from ..dependencies.auth import require_auth
from ..dependencies.threadpool import run_db_sync
from ..dependencies.rate_limit import limiter, _user_key
from ..template_config import templates

from datetime import datetime, timedelta, UTC
from typing import Any, Annotated

from loguru import logger
from sqlalchemy import case, func

from ...database.models import (
    Journal,
    Paper,
    PaperAppearance,
    RateLimitEstimate,
    ResearchHistory,
    ResearchRating,
    ResearchResource,
    ResearchStrategy,
    TokenUsage,
)
from ...constants import (
    get_available_strategies as get_central_available_strategies,
)
from ...domain_classifier import DomainClassifier, DomainClassification
from ...database.rekey_lock import RekeyOperationalError
from ...database.session_context import get_user_db_session
from ...metrics import TokenCounter
from ...metrics.query_utils import (
    get_context_overflow_truncation_summary,
    get_period_cutoff,
    get_period_days,
    get_time_filter_condition,
)
from ...metrics.search_tracker import get_search_tracker
from ...utilities.metric_write_health import (
    METRIC_WRITE_REASON_LABELS,
    get_metric_write_health,
)
from ...security import redact_url_for_log, url_authority_without_userinfo
from ..dependencies.json_body import json_body_error, read_json_dict
from .notes import _log_value_preview

# Create the router for metrics
router = APIRouter(prefix="/metrics", tags=["metrics"])

# NOTE: Routes use username (not .get()) intentionally.
# Depends(require_auth) guarantees the key exists; direct access fails
# fast if the dependency is ever removed.


def _extract_domain(url):
    """Extract normalized domain from URL, stripping www. prefix."""
    try:
        # Authority minus userinfo (empty when that is ambiguous),
        # matching DomainClassifier's key: the domain is returned to the
        # UI, logged and sent back to be classified and persisted.
        domain = url_authority_without_userinfo(url).lower()
        if domain.startswith("www."):
            domain = domain[4:]
        return domain if domain else None
    except (ValueError, AttributeError, TypeError):
        return None


def get_rating_analytics(period="30d", research_mode="all", username=None):
    """Get rating analytics for the specified period and research mode."""
    try:
        if not username:
            return {
                "rating_analytics": {
                    "avg_rating": None,
                    "total_ratings": 0,
                    "rating_distribution": {},
                    "satisfaction_stats": {
                        "very_satisfied": 0,
                        "satisfied": 0,
                        "neutral": 0,
                        "dissatisfied": 0,
                        "very_dissatisfied": 0,
                    },
                    "error": "No user session",
                }
            }

        # Calculate date range
        days = get_period_days(period)

        with get_user_db_session(username) as session:
            query = session.query(ResearchRating)

            # Apply time filter
            if days:
                cutoff_date = datetime.now(UTC) - timedelta(days=days)
                query = query.filter(ResearchRating.created_at >= cutoff_date)

            # Get all ratings
            ratings = query.all()

            if not ratings:
                return {
                    "rating_analytics": {
                        "avg_rating": None,
                        "total_ratings": 0,
                        "rating_distribution": {},
                        "satisfaction_stats": {
                            "very_satisfied": 0,
                            "satisfied": 0,
                            "neutral": 0,
                            "dissatisfied": 0,
                            "very_dissatisfied": 0,
                        },
                    }
                }

            # Calculate statistics
            rating_values = [r.rating for r in ratings]
            avg_rating = sum(rating_values) / len(rating_values)

            # Rating distribution
            rating_counts = {}
            for i in range(1, 6):
                rating_counts[str(i)] = rating_values.count(i)

            # Satisfaction categories
            satisfaction_stats = {
                "very_satisfied": rating_values.count(5),
                "satisfied": rating_values.count(4),
                "neutral": rating_values.count(3),
                "dissatisfied": rating_values.count(2),
                "very_dissatisfied": rating_values.count(1),
            }

            return {
                "rating_analytics": {
                    "avg_rating": round(avg_rating, 1),
                    "total_ratings": len(ratings),
                    "rating_distribution": rating_counts,
                    "satisfaction_stats": satisfaction_stats,
                }
            }

    except Exception:
        logger.exception("Error getting rating analytics")
        return {
            "rating_analytics": {
                "avg_rating": None,
                "total_ratings": 0,
                "rating_distribution": {},
                "satisfaction_stats": {
                    "very_satisfied": 0,
                    "satisfied": 0,
                    "neutral": 0,
                    "dissatisfied": 0,
                    "very_dissatisfied": 0,
                },
            }
        }


def get_link_analytics(period="30d", username=None):
    """Get link analytics from research resources."""
    try:
        if not username:
            return {
                "link_analytics": {
                    "top_domains": [],
                    "total_unique_domains": 0,
                    "avg_links_per_research": 0,
                    "domain_distribution": {},
                    "source_type_analysis": {},
                    "academic_vs_general": {},
                    "total_links": 0,
                    "error": "No user session",
                }
            }

        # Calculate date range
        days = get_period_days(period)

        with get_user_db_session(username) as session:
            # Project only the columns the analytics loop reads (url /
            # research_id / created_at / source_type / title) plus a SQL-level
            # boolean for whether content_preview is present. Loading full
            # ``ResearchResource`` entities would materialize the
            # ``content_preview`` Text column for every row on this whole-table
            # scan — which runs unfiltered when ``period=all`` (#4560).
            has_preview = (
                ResearchResource.content_preview.isnot(None)
                & (ResearchResource.content_preview != "")
            ).label("has_preview")
            query = session.query(
                ResearchResource.url,
                ResearchResource.research_id,
                ResearchResource.created_at,
                ResearchResource.source_type,
                ResearchResource.title,
                has_preview,
            )

            # Apply time filter
            if days:
                cutoff_date = datetime.now(UTC) - timedelta(days=days)
                query = query.filter(
                    ResearchResource.created_at >= cutoff_date.isoformat()
                )

            # Get all resources
            resources = query.all()

            if not resources:
                return {
                    "link_analytics": {
                        "top_domains": [],
                        "total_unique_domains": 0,
                        "avg_links_per_research": 0,
                        "domain_distribution": {},
                        "source_type_analysis": {},
                        "academic_vs_general": {},
                        "total_links": 0,
                    }
                }

            # Extract domains from URLs
            domain_counts: dict[str, Any] = {}
            domain_researches: dict[
                str, Any
            ] = {}  # Track which researches used each domain
            source_types: dict[str, Any] = {}
            temporal_data: dict[str, Any] = {}  # Track links over time
            domain_connections: dict[
                str, Any
            ] = {}  # Track domain co-occurrences

            # Generic category counting from LLM classifications
            category_counts: dict[str, Any] = {}

            quality_metrics = {
                "with_title": 0,
                "with_preview": 0,
                "with_both": 0,
                "total": 0,
            }

            # First pass: collect all domains from resources
            all_domains = set()
            for resource in resources:
                if resource.url:
                    domain = _extract_domain(resource.url)
                    if domain:
                        all_domains.add(domain)

            # Batch load all domain classifications in one query (fix N+1)
            domain_classifications_map = {}
            if all_domains:
                all_classifications = (
                    session.query(DomainClassification)
                    .filter(DomainClassification.domain.in_(all_domains))
                    .all()
                )
                for classification in all_classifications:
                    domain_classifications_map[classification.domain] = (
                        classification
                    )

            # Second pass: process resources with pre-loaded classifications
            for resource in resources:
                if resource.url:
                    try:
                        domain = _extract_domain(resource.url)
                        if not domain:
                            continue

                        # Count domains
                        domain_counts[domain] = domain_counts.get(domain, 0) + 1

                        # Track research IDs for each domain
                        if domain not in domain_researches:
                            domain_researches[domain] = set()
                        domain_researches[domain].add(resource.research_id)

                        # Track temporal data (daily counts)
                        if resource.created_at:
                            date_str = resource.created_at[
                                :10
                            ]  # Extract YYYY-MM-DD
                            temporal_data[date_str] = (
                                temporal_data.get(date_str, 0) + 1
                            )

                        # Count categories from pre-loaded classifications (no N+1)
                        classification = domain_classifications_map.get(domain)
                        if classification:
                            category = classification.category
                            category_counts[category] = (
                                category_counts.get(category, 0) + 1
                            )
                        else:
                            category_counts["Unclassified"] = (
                                category_counts.get("Unclassified", 0) + 1
                            )

                        # Track source type from metadata if available
                        if resource.source_type:
                            source_types[resource.source_type] = (
                                source_types.get(resource.source_type, 0) + 1
                            )

                        # Track quality metrics
                        quality_metrics["total"] += 1
                        if resource.title:
                            quality_metrics["with_title"] += 1
                        if resource.has_preview:
                            quality_metrics["with_preview"] += 1
                        if resource.title and resource.has_preview:
                            quality_metrics["with_both"] += 1

                        # Track domain co-occurrences for network visualization
                        research_id = resource.research_id
                        if research_id not in domain_connections:
                            domain_connections[research_id] = []
                        domain_connections[research_id].append(domain)

                    except Exception as e:
                        # Type name and redacted URL only: the exception
                        # text and traceback can carry the raw URL.
                        logger.warning(
                            "Error parsing URL "
                            f"{redact_url_for_log(resource.url)} "
                            f"({type(e).__name__})"
                        )

            # Sort domains by count and get top 10
            sorted_domains = sorted(
                domain_counts.items(), key=lambda x: x[1], reverse=True
            )
            top_10_domains = sorted_domains[:10]

            # Calculate domain distribution (top domains vs others)
            top_10_count = sum(count for _, count in top_10_domains)
            others_count = len(resources) - top_10_count

            # Get unique research IDs to calculate average
            unique_research_ids = {r.research_id for r in resources}
            avg_links = (
                len(resources) / len(unique_research_ids)
                if unique_research_ids
                else 0
            )

            # Prepare temporal trend data (sorted by date)
            temporal_trend = sorted(
                [
                    {"date": date, "count": count}
                    for date, count in temporal_data.items()
                ],
                key=lambda x: x["date"],
            )

            # Get most recent research for each top domain and classifications
            domain_recent_research = {}
            # Build domain_classifications dict from pre-loaded data
            domain_classifications = {
                domain: {
                    "category": classification.category,
                    "subcategory": classification.subcategory,
                    "confidence": classification.confidence,
                }
                for domain, classification in domain_classifications_map.items()
            }

            # Batch-load research details for top domains (fix N+1 query)
            all_research_ids = []
            domain_research_id_lists = {}
            for domain, _ in top_10_domains:
                if domain in domain_researches:
                    ids = list(domain_researches[domain])[:3]
                    domain_research_id_lists[domain] = ids
                    all_research_ids.extend(ids)

            research_by_id = {}
            if all_research_ids:
                researches = (
                    session.query(ResearchHistory)
                    .filter(ResearchHistory.id.in_(all_research_ids))
                    .all()
                )
                research_by_id = {r.id: r for r in researches}

            for domain, ids in domain_research_id_lists.items():
                domain_recent_research[domain] = [
                    {
                        "id": r_id,
                        "query": research_by_id[r_id].query[:50]
                        if research_by_id.get(r_id)
                        and research_by_id[r_id].query
                        else "Research",
                    }
                    for r_id in ids
                    if r_id in research_by_id
                ]

            return {
                "link_analytics": {
                    "top_domains": [
                        {
                            "domain": domain,
                            "count": count,
                            "percentage": round(
                                count / len(resources) * 100, 1
                            ),
                            "research_count": len(
                                domain_researches.get(domain, set())
                            ),
                            "recent_researches": domain_recent_research.get(
                                domain, []
                            ),
                            "classification": domain_classifications.get(
                                domain, None
                            ),
                        }
                        for domain, count in top_10_domains
                    ],
                    "total_unique_domains": len(domain_counts),
                    "avg_links_per_research": round(avg_links, 1),
                    "domain_distribution": {
                        "top_10": top_10_count,
                        "others": others_count,
                    },
                    "source_type_analysis": source_types,
                    "category_distribution": category_counts,
                    # Generic pie chart data - use whatever LLM classifier outputs
                    "domain_categories": category_counts,
                    "total_links": len(resources),
                    "total_researches": len(unique_research_ids),
                    "temporal_trend": temporal_trend,
                    "domain_metrics": {
                        domain: {
                            "usage_count": count,
                            "usage_percentage": round(
                                count / len(resources) * 100, 1
                            ),
                            "research_diversity": len(
                                domain_researches.get(domain, set())
                            ),
                            "frequency_rank": rank + 1,
                        }
                        for rank, (domain, count) in enumerate(top_10_domains)
                    },
                }
            }

    except Exception:
        logger.exception("Error getting link analytics")
        return {
            "link_analytics": {
                "top_domains": [],
                "total_unique_domains": 0,
                "avg_links_per_research": 0,
                "domain_distribution": {},
                "source_type_analysis": {},
                "academic_vs_general": {},
                "total_links": 0,
                "error": "Failed to retrieve link analytics",
            }
        }


def get_available_strategies():
    """Get list of all available search strategies, for the analytics UI.

    Derived from ``constants.AVAILABLE_STRATEGIES`` -- the single
    app-wide source of truth for UI-facing strategies (also consumed by
    ``search_system_factory.create_strategy``, the settings UI, the news
    subscription form, and the MCP server). This function only adapts the
    shape: it keeps this endpoint's existing ``{"name", "description"}``
    wire contract by dropping the ``"label"`` field that the central list
    carries for dropdown widgets, so response consumers are unaffected.

    Do not hand-maintain a separate strategy list here -- add new
    strategies to ``AVAILABLE_STRATEGIES`` in constants.py instead.
    """
    return [
        {"name": strategy["name"], "description": strategy["description"]}
        for strategy in get_central_available_strategies()
    ]


def get_strategy_analytics(period="30d", username=None):
    """Get strategy usage analytics for the specified period."""
    try:
        if not username:
            return {
                "strategy_analytics": {
                    "total_research_with_strategy": 0,
                    "total_research": 0,
                    "most_popular_strategy": None,
                    "strategy_usage": [],
                    "strategy_distribution": {},
                    "available_strategies": get_available_strategies(),
                    "error": "No user session",
                }
            }

        # Calculate date range
        days = get_period_days(period)

        with get_user_db_session(username) as session:
            # Check if we have any ResearchStrategy records
            strategy_count = session.query(ResearchStrategy).count()

            if strategy_count == 0:
                logger.warning("No research strategies found in database")
                return {
                    "strategy_analytics": {
                        "total_research_with_strategy": 0,
                        "total_research": 0,
                        "most_popular_strategy": None,
                        "strategy_usage": [],
                        "strategy_distribution": {},
                        "available_strategies": get_available_strategies(),
                        "message": "Strategy tracking not yet available - run a research to start tracking",
                    }
                }

            # Base query for strategy usage (no JOIN needed since we just want strategy counts)
            query = session.query(
                ResearchStrategy.strategy_name,
                func.count(ResearchStrategy.id).label("usage_count"),
            )

            # Apply time filter if specified
            if days:
                cutoff_date = datetime.now(UTC) - timedelta(days=days)
                query = query.filter(ResearchStrategy.created_at >= cutoff_date)

            # Group by strategy and order by usage
            strategy_results = (
                query.group_by(ResearchStrategy.strategy_name)
                .order_by(func.count(ResearchStrategy.id).desc())
                .all()
            )

            # Get total strategy count for percentage calculation
            total_query = session.query(ResearchStrategy)
            if days:
                total_query = total_query.filter(
                    ResearchStrategy.created_at >= cutoff_date
                )
            total_research = total_query.count()

            # Format strategy data
            strategy_usage = []
            strategy_distribution = {}

            for strategy_name, usage_count in strategy_results:
                percentage = (
                    (usage_count / total_research * 100)
                    if total_research > 0
                    else 0
                )
                strategy_usage.append(
                    {
                        "strategy": strategy_name,
                        "count": usage_count,
                        "percentage": round(percentage, 1),
                    }
                )
                strategy_distribution[strategy_name] = usage_count

            # Find most popular strategy
            most_popular = (
                strategy_usage[0]["strategy"] if strategy_usage else None
            )

            return {
                "strategy_analytics": {
                    "total_research_with_strategy": sum(
                        item["count"] for item in strategy_usage
                    ),
                    "total_research": total_research,
                    "most_popular_strategy": most_popular,
                    "strategy_usage": strategy_usage,
                    "strategy_distribution": strategy_distribution,
                    "available_strategies": get_available_strategies(),
                }
            }

    except Exception:
        logger.exception("Error getting strategy analytics")
        return {
            "strategy_analytics": {
                "total_research_with_strategy": 0,
                "total_research": 0,
                "most_popular_strategy": None,
                "strategy_usage": [],
                "strategy_distribution": {},
                "available_strategies": get_available_strategies(),
                "error": "Failed to retrieve strategy data",
            }
        }


def get_rate_limiting_analytics(period="30d", username=None):
    """Get rate limiting analytics for the specified period."""
    try:
        if not username:
            return {
                "rate_limiting": {
                    "total_attempts": 0,
                    "successful_attempts": 0,
                    "failed_attempts": 0,
                    "success_rate": 0,
                    "rate_limit_events": 0,
                    "avg_wait_time": 0,
                    "avg_successful_wait": 0,
                    "tracked_engines": 0,
                    "engine_stats": [],
                    "total_engines_tracked": 0,
                    "healthy_engines": 0,
                    "degraded_engines": 0,
                    "poor_engines": 0,
                    "error": "No user session",
                }
            }

        # Calculate date range for timestamp filtering. Same single source
        # of truth as the token window (PERIOD_DAYS_MAP via
        # get_period_cutoff) — the local 7d/30d/3m/1y ladder this replaces
        # computed ALL-TIME for any other period string ('90d', '365d', or
        # an unknown value) while the token window in the same /api/metrics
        # response was bounded (#6942). This dict is spread after the token
        # metrics there, so its 'rate_limiting' value is the one served.
        cutoff_dt = get_period_cutoff(period)
        cutoff_time = cutoff_dt.timestamp() if cutoff_dt is not None else 0

        with get_user_db_session(username) as session:
            # Rate-limit analytics are derived from RateLimitEstimate, the
            # learned per-engine wait-time model that production code
            # actually persists. The raw per-attempt table
            # (RateLimitAttempt) is intentionally NOT written — attempt
            # persistence was disabled (commit fef359be9) to avoid DB
            # locking under parallel search — so the previous code, which
            # read RateLimitAttempt, always returned an empty panel.
            #
            # Limitations of deriving from estimates (documented so the
            # numbers aren't mistaken for raw-attempt counts):
            #   - total_attempts is each engine's recent rolling window
            #     (capped at rate_limiting.memory_window, default 100), not
            #     a lifetime count.
            #   - rate_limit_events (RateLimitError-specific failures) and a
            #     true per-attempt average wait cannot be reconstructed and
            #     are reported as 0 / the learned base wait respectively.
            estimates_query = session.query(RateLimitEstimate)

            # Recency filter uses the estimate's last_updated (epoch
            # seconds); there is no per-attempt timestamp history.
            if cutoff_time > 0:
                estimates_query = estimates_query.filter(
                    RateLimitEstimate.last_updated >= cutoff_time
                )

            estimates = estimates_query.all()

            engine_stats = []
            total_attempts = 0
            successful_attempts = 0
            base_wait_sum = 0.0

            for estimate in estimates:
                # success_rate is stored as a 0..1 fraction.
                success_rate_pct = round(estimate.success_rate * 100, 1)
                engine_attempts = estimate.total_attempts or 0
                engine_success = round(engine_attempts * estimate.success_rate)

                total_attempts += engine_attempts
                successful_attempts += engine_success
                base_wait_sum += estimate.base_wait_seconds

                status = (
                    "healthy"
                    if estimate.success_rate > 0.8
                    else "degraded"
                    if estimate.success_rate > 0.5
                    else "poor"
                )

                engine_stats.append(
                    {
                        "engine": estimate.engine_type,
                        "base_wait": estimate.base_wait_seconds,
                        "base_wait_seconds": round(
                            estimate.base_wait_seconds, 2
                        ),
                        "min_wait_seconds": round(estimate.min_wait_seconds, 2),
                        "max_wait_seconds": round(estimate.max_wait_seconds, 2),
                        "success_rate": success_rate_pct,
                        "total_attempts": engine_attempts,
                        "recent_attempts": engine_attempts,
                        "recent_success_rate": success_rate_pct,
                        "attempts": engine_attempts,
                        "status": status,
                        # ISO format already includes timezone
                        "last_updated": datetime.fromtimestamp(
                            estimate.last_updated, UTC
                        ).isoformat(),
                    }
                )

            tracked_engines = len(engine_stats)
            failed_attempts = total_attempts - successful_attempts
            # base_wait_seconds is the learned optimal (median of recent
            # successful waits), so it represents both the typical wait and
            # the typical successful wait; a true per-attempt average needs
            # the raw attempts table.
            avg_wait_time = (
                base_wait_sum / tracked_engines if tracked_engines else 0
            )
            avg_successful_wait = avg_wait_time
            # Not derivable from estimates (needs the raw attempts table).
            rate_limit_events = 0

            logger.info(
                f"Rate limiting analytics from estimates: "
                f"tracked_engines={tracked_engines}, "
                f"total_attempts(recent)={total_attempts}"
            )

            result = {
                "rate_limiting": {
                    "total_attempts": total_attempts,
                    "successful_attempts": successful_attempts,
                    "failed_attempts": failed_attempts,
                    "success_rate": (successful_attempts / total_attempts * 100)
                    if total_attempts > 0
                    else 0,
                    "rate_limit_events": rate_limit_events,
                    "avg_wait_time": round(float(avg_wait_time), 2),
                    "avg_successful_wait": round(float(avg_successful_wait), 2),
                    "tracked_engines": tracked_engines,
                    "engine_stats": engine_stats,
                    "total_engines_tracked": tracked_engines,
                    "healthy_engines": len(
                        [s for s in engine_stats if s["status"] == "healthy"]
                    ),
                    "degraded_engines": len(
                        [s for s in engine_stats if s["status"] == "degraded"]
                    ),
                    "poor_engines": len(
                        [s for s in engine_stats if s["status"] == "poor"]
                    ),
                }
            }

            logger.info(
                f"DEBUG: Returning rate_limiting_analytics result: {result}"
            )
            return result

    except Exception:
        logger.exception("Error getting rate limiting analytics")
        return {
            "rate_limiting": {
                "total_attempts": 0,
                "successful_attempts": 0,
                "failed_attempts": 0,
                "success_rate": 0,
                "rate_limit_events": 0,
                "avg_wait_time": 0,
                "avg_successful_wait": 0,
                "tracked_engines": 0,
                "engine_stats": [],
                "total_engines_tracked": 0,
                "healthy_engines": 0,
                "degraded_engines": 0,
                "poor_engines": 0,
                "error": "An internal error occurred while processing the request.",
            }
        }


@router.get("/")
def metrics_dashboard(
    request: Request, username: Annotated[str, Depends(require_auth)]
):
    """Render the metrics dashboard page."""
    return templates.TemplateResponse(
        request=request,
        name="pages/metrics.html",
        context={
            "request": request,
            "metric_write_health": get_metric_write_health(username),
            "metric_write_reason_labels": METRIC_WRITE_REASON_LABELS,
        },
    )


@router.get("/context-overflow")
def context_overflow_page(
    request: Request, username: Annotated[str, Depends(require_auth)]
):
    """Context overflow analytics page."""
    return templates.TemplateResponse(
        request=request,
        name="pages/context_overflow.html",
        context={"request": request},
    )


@router.get("/api/metrics")
def api_metrics(
    request: Request, username: Annotated[str, Depends(require_auth)]
):
    """Get overall metrics data."""
    logger.debug("api_metrics endpoint called")
    try:
        # Get username from session

        # Get time period and research mode from query parameters
        period = request.query_params.get("period", "30d")
        research_mode = request.query_params.get("mode", "all")

        token_counter = TokenCounter()
        search_tracker = get_search_tracker()

        # Get both token and search metrics
        token_metrics = token_counter.get_overall_metrics(
            period=period, research_mode=research_mode, username=username
        )
        search_metrics = search_tracker.get_search_metrics(
            period=period,
            research_mode=research_mode,
            username=username,
        )

        # Get user satisfaction rating data
        try:
            with get_user_db_session(username) as session:
                # Build base query with time filter
                ratings_query = session.query(ResearchRating)
                time_condition = get_time_filter_condition(
                    period, ResearchRating.created_at
                )
                if time_condition is not None:
                    ratings_query = ratings_query.filter(time_condition)

                # Get average rating
                avg_rating = ratings_query.with_entities(
                    func.avg(ResearchRating.rating).label("avg_rating")
                ).scalar()

                # Get total rating count
                total_ratings = ratings_query.count()

                user_satisfaction = {
                    "avg_rating": round(avg_rating, 1) if avg_rating else None,
                    "total_ratings": total_ratings,
                }
        except Exception:
            logger.exception("Error getting user satisfaction data")
            user_satisfaction = {"avg_rating": None, "total_ratings": 0}

        # Get strategy analytics
        strategy_data = get_strategy_analytics(period, username)
        logger.debug(f"strategy_data keys: {list(strategy_data.keys())}")

        # Get rate limiting analytics
        rate_limiting_data = get_rate_limiting_analytics(period, username)
        logger.debug(f"rate_limiting_data: {rate_limiting_data}")
        logger.debug(
            f"rate_limiting_data keys: {list(rate_limiting_data.keys())}"
        )

        # Truncation summary surfaced on the main dashboard. Failure sentinel
        # is None (not 0): a real zero means "no truncation", so falling back
        # to 0 on error would silently flip a red signal green.
        context_overflow_data = {
            "truncation_rate": None,
            "avg_tokens_truncated": None,
        }
        try:
            with get_user_db_session(username) as session:
                # Honor the dashboard's research_mode filter the same way the
                # rest of api_metrics() does (token_metrics, search_metrics,
                # etc.). Without this the panel ignores mode toggles.
                summary = get_context_overflow_truncation_summary(
                    session, period, research_mode=research_mode
                )
            context_overflow_data = {
                "truncation_rate": round(summary["truncation_rate"], 1),
                "avg_tokens_truncated": int(summary["avg_tokens_truncated"]),
            }
        except Exception:
            logger.exception(
                "Error getting context overflow summary for /api/metrics"
            )

        # Combine metrics
        combined_metrics = {
            **token_metrics,
            **search_metrics,
            **strategy_data,
            **rate_limiting_data,
            **context_overflow_data,
            "user_satisfaction": user_satisfaction,
        }

        logger.debug(f"combined_metrics keys: {list(combined_metrics.keys())}")
        logger.debug(
            f"combined_metrics['rate_limiting']: {combined_metrics.get('rate_limiting', 'NOT FOUND')}"
        )

        return {
            "status": "success",
            "metrics": combined_metrics,
            "period": period,
            "research_mode": research_mode,
        }

    except Exception:
        logger.exception("Error getting metrics")
        return JSONResponse(
            {
                "status": "error",
                "message": "An internal error occurred. Please try again later.",
            },
            status_code=500,
        )


@router.get("/api/rate-limiting")
def get_rate_limiting_metrics(
    request: Request, username: Annotated[str, Depends(require_auth)]
):
    """Get detailed rate limiting metrics."""
    logger.info("DEBUG: get_rate_limiting_metrics endpoint called")
    try:
        period = request.query_params.get("period", "30d")
        rate_limiting_data = get_rate_limiting_analytics(period, username)

        return {
            "status": "success",
            "data": rate_limiting_data,
            "period": period,
        }

    except Exception:
        logger.exception("Error getting rate limiting metrics")
        return JSONResponse(
            {
                "status": "error",
                "message": "Failed to retrieve rate limiting metrics",
            },
            status_code=500,
        )


@router.get("/api/rate-limiting/current")
def api_current_rate_limits(
    request: Request, username: Annotated[str, Depends(require_auth)]
):
    """Get current rate limit estimates for all engines."""
    try:
        with get_user_db_session(username) as session:
            estimates = (
                session.query(RateLimitEstimate)
                .order_by(RateLimitEstimate.engine_type)
                .all()
            )

            current_limits = []
            for est in estimates:
                current_limits.append(
                    {
                        "engine_type": est.engine_type,
                        "base_wait_seconds": round(est.base_wait_seconds, 2),
                        "min_wait_seconds": round(est.min_wait_seconds, 2),
                        "max_wait_seconds": round(est.max_wait_seconds, 2),
                        "success_rate": round(est.success_rate * 100, 1),
                        "total_attempts": est.total_attempts,
                        "last_updated": datetime.fromtimestamp(
                            est.last_updated, UTC
                        ).isoformat(),
                        "status": "healthy"
                        if est.success_rate > 0.8
                        else "degraded"
                        if est.success_rate > 0.5
                        else "poor",
                    }
                )

        return {
            "status": "success",
            "current_limits": current_limits,
            "timestamp": datetime.now(UTC).isoformat(),
        }
    except Exception:
        logger.exception("Error getting current rate limits")
        return JSONResponse(
            {
                "status": "error",
                "message": "Failed to retrieve current rate limits",
            },
            status_code=500,
        )


@router.get("/api/metrics/research/{research_id}/links")
def api_research_link_metrics(
    request: Request,
    research_id,
    username: Annotated[str, Depends(require_auth)],
):
    """Get link analytics for a specific research."""
    try:
        with get_user_db_session(username) as session:
            # Get all resources for this specific research
            resources = (
                session.query(ResearchResource)
                .filter(ResearchResource.research_id == research_id)
                .all()
            )

            if not resources:
                return {
                    "status": "success",
                    "data": {
                        "total_links": 0,
                        "unique_domains": 0,
                        "domains": [],
                        "category_distribution": {},
                        "domain_categories": {},
                        "resources": [],
                    },
                }

            # Extract domain information
            domain_counts: dict[str, Any] = {}

            # Generic category counting from LLM classifications
            category_counts: dict[str, Any] = {}

            # First pass: collect all domains
            all_domains = set()
            for resource in resources:
                if resource.url:
                    domain = _extract_domain(resource.url)
                    if domain:
                        all_domains.add(domain)

            # Batch load all domain classifications in one query (fix N+1)
            domain_classifications_map = {}
            if all_domains:
                all_classifications = (
                    session.query(DomainClassification)
                    .filter(DomainClassification.domain.in_(all_domains))
                    .all()
                )
                for classification in all_classifications:
                    domain_classifications_map[classification.domain] = (
                        classification
                    )

            # Second pass: process resources with pre-loaded classifications
            for resource in resources:
                if resource.url:
                    try:
                        domain = _extract_domain(resource.url)
                        if not domain:
                            continue

                        domain_counts[domain] = domain_counts.get(domain, 0) + 1

                        # Count categories from pre-loaded classifications (no N+1)
                        classification = domain_classifications_map.get(domain)
                        if classification:
                            category = classification.category
                            category_counts[category] = (
                                category_counts.get(category, 0) + 1
                            )
                        else:
                            category_counts["Unclassified"] = (
                                category_counts.get("Unclassified", 0) + 1
                            )
                    except (AttributeError, KeyError) as e:
                        logger.debug(
                            f"Error classifying domain {domain}: "
                            f"{type(e).__name__}"
                        )

            # Sort domains by count
            sorted_domains = sorted(
                domain_counts.items(), key=lambda x: x[1], reverse=True
            )

            return {
                "status": "success",
                "data": {
                    "total_links": len(resources),
                    "unique_domains": len(domain_counts),
                    "domains": [
                        {
                            "domain": domain,
                            "count": count,
                            "percentage": round(
                                count / len(resources) * 100, 1
                            ),
                        }
                        for domain, count in sorted_domains[
                            :20
                        ]  # Top 20 domains
                    ],
                    "category_distribution": category_counts,
                    "domain_categories": category_counts,  # Generic categories from LLM
                    "resources": [
                        {
                            "title": r.title or "Untitled",
                            "url": r.url,
                            "preview": r.content_preview[:200]
                            if r.content_preview
                            else None,
                        }
                        for r in resources[:10]  # First 10 resources
                    ],
                },
            }

    except Exception:
        logger.exception("Error getting research link metrics")
        return JSONResponse(
            {"status": "error", "message": "Failed to retrieve link metrics"},
            status_code=500,
        )


@router.get("/api/metrics/research/{research_id}")
def api_research_metrics(
    request: Request,
    research_id,
    username: Annotated[str, Depends(require_auth)],
):
    """Get metrics for a specific research."""
    try:
        token_counter = TokenCounter()
        metrics = token_counter.get_research_metrics(
            research_id, username=username
        )
        return {"status": "success", "metrics": metrics}
    except Exception:
        logger.exception("Error getting research metrics")
        return JSONResponse(
            {
                "status": "error",
                "message": "An internal error occurred. Please try again later.",
            },
            status_code=500,
        )


@router.get("/api/metrics/research/{research_id}/timeline")
def api_research_timeline_metrics(
    request: Request,
    research_id,
    username: Annotated[str, Depends(require_auth)],
):
    """Get timeline metrics for a specific research."""
    try:
        token_counter = TokenCounter()
        timeline_metrics = token_counter.get_research_timeline_metrics(
            research_id, username=username
        )
        return {"status": "success", "metrics": timeline_metrics}
    except Exception:
        logger.exception("Error getting research timeline metrics")
        return JSONResponse(
            {
                "status": "error",
                "message": "An internal error occurred. Please try again later.",
            },
            status_code=500,
        )


@router.get("/api/metrics/research/{research_id}/search")
def api_research_search_metrics(
    request: Request,
    research_id,
    username: Annotated[str, Depends(require_auth)],
):
    """Get search metrics for a specific research."""
    try:
        search_tracker = get_search_tracker()
        search_metrics = search_tracker.get_research_search_metrics(
            research_id, username=username
        )
        return {"status": "success", "metrics": search_metrics}
    except Exception:
        logger.exception("Error getting research search metrics")
        return JSONResponse(
            {
                "status": "error",
                "message": "An internal error occurred. Please try again later.",
            },
            status_code=500,
        )


@router.get("/api/metrics/enhanced")
def api_enhanced_metrics(
    request: Request, username: Annotated[str, Depends(require_auth)]
):
    """Get enhanced Phase 1 tracking metrics."""
    try:
        # Get time period and research mode from query parameters
        period = request.query_params.get("period", "30d")
        research_mode = request.query_params.get("mode", "all")

        token_counter = TokenCounter()
        search_tracker = get_search_tracker()

        enhanced_metrics = token_counter.get_enhanced_metrics(
            period=period, research_mode=research_mode, username=username
        )

        # Add search time series data for the chart
        search_time_series = search_tracker.get_search_time_series(
            period=period,
            research_mode=research_mode,
            username=username,
        )
        enhanced_metrics["search_time_series"] = search_time_series

        # Add rating analytics
        rating_analytics = get_rating_analytics(period, research_mode, username)
        enhanced_metrics.update(rating_analytics)

        return {
            "status": "success",
            "metrics": enhanced_metrics,
            "period": period,
            "research_mode": research_mode,
        }

    except Exception:
        logger.exception("Error getting enhanced metrics")
        return JSONResponse(
            {
                "status": "error",
                "message": "An internal error occurred. Please try again later.",
            },
            status_code=500,
        )


@router.get("/api/ratings/{research_id}")
def api_get_research_rating(
    request: Request,
    research_id,
    username: Annotated[str, Depends(require_auth)],
):
    """Get rating for a specific research session."""
    try:
        with get_user_db_session(username) as session:
            rating = (
                session.query(ResearchRating)
                .filter_by(research_id=research_id)
                .first()
            )

            if rating:
                return {
                    "status": "success",
                    "rating": rating.rating,
                    "created_at": rating.created_at.isoformat(),
                    "updated_at": rating.updated_at.isoformat(),
                }
            return {"status": "success", "rating": None}

    except Exception:
        logger.exception("Error getting research rating")
        return JSONResponse(
            {
                "status": "error",
                "message": "An internal error occurred. Please try again later.",
            },
            status_code=500,
        )


@router.post("/api/ratings/{research_id}")
async def api_save_research_rating(
    request: Request,
    research_id,
    username: Annotated[str, Depends(require_auth)],
):
    """Save or update rating for a specific research session."""
    # Parse before the broad exception handler so malformed bodies retain
    # this route's validation envelope instead of becoming server errors.
    data, body_error = await read_json_dict(
        request, "status", "Request body must be valid JSON"
    )
    if body_error is not None:
        return body_error
    try:
        rating_value = data.get("rating")

        if (
            not isinstance(rating_value, int)
            or isinstance(rating_value, bool)
            or rating_value < 1
            or rating_value > 5
        ):
            return JSONResponse(
                {
                    "status": "error",
                    "message": "Rating must be an integer between 1 and 5",
                },
                status_code=400,
            )

        # Optional sub-dimension fields (1-5)
        sub_dimensions = {}
        for field in ("accuracy", "completeness", "relevance", "readability"):
            val = data.get(field)
            if val is not None:
                if (
                    not isinstance(val, int)
                    or isinstance(val, bool)
                    or val < 1
                    or val > 5
                ):
                    return JSONResponse(
                        {
                            "status": "error",
                            "message": f"{field} must be an integer between 1 and 5",
                        },
                        status_code=400,
                    )
                sub_dimensions[field] = val

        feedback_text = data.get("feedback")
        if feedback_text is not None:
            if not isinstance(feedback_text, str):
                return JSONResponse(
                    {
                        "status": "error",
                        "message": "feedback must be a string",
                    },
                    status_code=400,
                )
            if len(feedback_text) > 10000:
                return JSONResponse(
                    {
                        "status": "error",
                        "message": "feedback must be 10000 characters or fewer",
                    },
                    status_code=400,
                )

        def _save_sync():
            with get_user_db_session(username) as session:
                existing_rating = (
                    session.query(ResearchRating)
                    .filter_by(research_id=research_id)
                    .first()
                )
                if existing_rating:
                    existing_rating.rating = rating_value
                    existing_rating.updated_at = func.now()
                    for field, val in sub_dimensions.items():
                        setattr(existing_rating, field, val)
                    if feedback_text is not None:
                        existing_rating.feedback = feedback_text
                else:
                    session.add(
                        ResearchRating(
                            research_id=research_id,
                            rating=rating_value,
                            feedback=feedback_text,
                            **sub_dimensions,
                        )
                    )
                session.commit()

        await run_db_sync(_save_sync)
        return {
            "status": "success",
            "message": "Rating saved successfully",
            "rating": rating_value,
        }

    except Exception:
        logger.exception("Error saving research rating")
        return JSONResponse(
            {
                "status": "error",
                "message": "An internal error occurred. Please try again later.",
            },
            status_code=500,
        )


@router.get("/star-reviews")
def star_reviews(
    request: Request, username: Annotated[str, Depends(require_auth)]
):
    """Display star reviews metrics page."""
    return templates.TemplateResponse(
        request=request,
        name="pages/star_reviews.html",
        context={"request": request},
    )


@router.get("/costs")
def cost_analytics(
    request: Request, username: Annotated[str, Depends(require_auth)]
):
    """Display cost analytics page."""
    return templates.TemplateResponse(
        request=request,
        name="pages/cost_analytics.html",
        context={"request": request},
    )


@router.get("/api/star-reviews")
def api_star_reviews(
    request: Request, username: Annotated[str, Depends(require_auth)]
):
    """Get star reviews analytics data."""
    try:
        period = request.query_params.get("period", "30d")

        with get_user_db_session(username) as session:
            # Build base query with time filter
            base_query = session.query(ResearchRating)
            time_condition = get_time_filter_condition(
                period, ResearchRating.created_at
            )
            if time_condition is not None:
                base_query = base_query.filter(time_condition)

            # Overall rating statistics
            overall_stats = session.query(
                func.avg(ResearchRating.rating).label("avg_rating"),
                func.count(ResearchRating.rating).label("total_ratings"),
                func.sum(case((ResearchRating.rating == 5, 1), else_=0)).label(
                    "five_star"
                ),
                func.sum(case((ResearchRating.rating == 4, 1), else_=0)).label(
                    "four_star"
                ),
                func.sum(case((ResearchRating.rating == 3, 1), else_=0)).label(
                    "three_star"
                ),
                func.sum(case((ResearchRating.rating == 2, 1), else_=0)).label(
                    "two_star"
                ),
                func.sum(case((ResearchRating.rating == 1, 1), else_=0)).label(
                    "one_star"
                ),
            )

            if time_condition is not None:
                overall_stats = overall_stats.filter(time_condition)

            overall_stats = overall_stats.first()

            # Ratings by LLM model. A research has many token_usage rows (one per
            # LLM call), so joining TokenUsage directly fans out and multiplies the
            # counts/averages. Collapse to distinct (research_id, model) pairs first
            # so each rating is counted once per model it actually used.
            # Normalize the "missing model" sentinels — empty/whitespace and the
            # lowercase "unknown" fallback the token counter writes — to a single
            # "Unknown" *inside* the subquery, so DISTINCT dedups on the normalized
            # value. (Normalizing only at group_by time lets "" and "unknown"
            # survive DISTINCT as separate rows and double-count one rating into the
            # merged bucket.) Real model names keep their original casing via else_.
            normalized_model = case(
                (
                    func.lower(func.trim(TokenUsage.model_name)).in_(
                        ["", "unknown"]
                    ),
                    "Unknown",
                ),
                else_=TokenUsage.model_name,
            )
            research_models = (
                session.query(
                    TokenUsage.research_id.label("research_id"),
                    normalized_model.label("model_name"),
                )
                .distinct()
                .subquery()
            )
            # A rating with no token rows has no subquery match -> NULL via the
            # outerjoin -> "Unknown".
            model_label = func.coalesce(research_models.c.model_name, "Unknown")

            llm_ratings_query = (
                session.query(
                    model_label.label("model"),
                    func.avg(ResearchRating.rating).label("avg_rating"),
                    func.count(ResearchRating.rating).label("rating_count"),
                    func.sum(
                        case((ResearchRating.rating >= 4, 1), else_=0)
                    ).label("positive_ratings"),
                    func.sum(
                        case((ResearchRating.rating == 3, 1), else_=0)
                    ).label("neutral_ratings"),
                    func.sum(
                        case((ResearchRating.rating <= 2, 1), else_=0)
                    ).label("negative_ratings"),
                )
                .select_from(ResearchRating)
                .outerjoin(
                    research_models,
                    ResearchRating.research_id == research_models.c.research_id,
                )
            )

            if time_condition is not None:
                llm_ratings_query = llm_ratings_query.filter(time_condition)

            llm_ratings = (
                llm_ratings_query.group_by(model_label)
                .order_by(func.avg(ResearchRating.rating).desc())
                .all()
            )

            # Ratings by search engine. Same one-to-many fan-out concern as the LLM
            # query — collapse to distinct (research_id, search_engine) pairs first.
            # search_engine_selected is NULL on non-search LLM-call rows (and is
            # occasionally an empty/whitespace string); exclude both so a research
            # that used a real engine isn't ALSO attributed to the "Unknown" bucket.
            # A research with no recorded engine still falls through the outerjoin to
            # "Unknown" exactly once.
            research_engines = (
                session.query(
                    TokenUsage.research_id.label("research_id"),
                    TokenUsage.search_engine_selected.label("search_engine"),
                )
                .filter(
                    func.trim(
                        func.coalesce(TokenUsage.search_engine_selected, "")
                    )
                    != ""
                )
                .distinct()
                .subquery()
            )
            engine_label = func.coalesce(
                research_engines.c.search_engine, "Unknown"
            )

            search_engine_ratings_query = (
                session.query(
                    engine_label.label("search_engine"),
                    func.avg(ResearchRating.rating).label("avg_rating"),
                    func.count(ResearchRating.rating).label("rating_count"),
                    func.sum(
                        case((ResearchRating.rating >= 4, 1), else_=0)
                    ).label("positive_ratings"),
                )
                .select_from(ResearchRating)
                .outerjoin(
                    research_engines,
                    ResearchRating.research_id
                    == research_engines.c.research_id,
                )
            )

            if time_condition is not None:
                search_engine_ratings_query = (
                    search_engine_ratings_query.filter(time_condition)
                )

            search_engine_ratings = (
                search_engine_ratings_query.group_by(engine_label)
                .having(func.count(ResearchRating.rating) > 0)
                .order_by(func.avg(ResearchRating.rating).desc())
                .all()
            )

            # Rating trends over time
            rating_trends_query = session.query(
                func.date(ResearchRating.created_at).label("date"),
                func.avg(ResearchRating.rating).label("avg_rating"),
                func.count(ResearchRating.rating).label("daily_count"),
            )

            if time_condition is not None:
                rating_trends_query = rating_trends_query.filter(time_condition)

            rating_trends = (
                rating_trends_query.group_by(
                    func.date(ResearchRating.created_at)
                )
                .order_by("date")
                .all()
            )

            # Ratings by research mode
            mode_ratings_query = session.query(
                func.coalesce(ResearchHistory.mode, "Unknown").label("mode"),
                func.avg(ResearchRating.rating).label("avg_rating"),
                func.count(ResearchRating.rating).label("rating_count"),
                func.sum(case((ResearchRating.rating >= 4, 1), else_=0)).label(
                    "positive_ratings"
                ),
            ).outerjoin(
                ResearchHistory,
                ResearchRating.research_id == ResearchHistory.id,
            )

            if time_condition is not None:
                mode_ratings_query = mode_ratings_query.filter(time_condition)

            mode_ratings = (
                mode_ratings_query.group_by(ResearchHistory.mode)
                .having(func.count(ResearchRating.rating) > 0)
                .order_by(func.avg(ResearchRating.rating).desc())
                .all()
            )

            # Quality dimension averages. Each sub-dimension is independently
            # nullable, so count them separately; dimension_count reflects rows
            # with ANY dimension filled, so the radar isn't hidden when only some
            # dimensions have data.
            dimension_stats = session.query(
                func.avg(ResearchRating.accuracy).label("avg_accuracy"),
                func.avg(ResearchRating.completeness).label("avg_completeness"),
                func.avg(ResearchRating.relevance).label("avg_relevance"),
                func.avg(ResearchRating.readability).label("avg_readability"),
                func.count(ResearchRating.accuracy).label("count_accuracy"),
                func.count(ResearchRating.completeness).label(
                    "count_completeness"
                ),
                func.count(ResearchRating.relevance).label("count_relevance"),
                func.count(ResearchRating.readability).label(
                    "count_readability"
                ),
                func.count(
                    func.coalesce(
                        ResearchRating.accuracy,
                        ResearchRating.completeness,
                        ResearchRating.relevance,
                        ResearchRating.readability,
                    )
                ).label("dimension_count"),
            )

            if time_condition is not None:
                dimension_stats = dimension_stats.filter(time_condition)

            dimension_stats = dimension_stats.first()

            # Recent ratings with research details. Join a one-row-per-research
            # model subquery instead of TokenUsage directly: a research has many
            # token_usage rows, which would fan out and make limit(20) return far
            # fewer than 20 unique ratings (the same rating duplicated per row).
            recent_model_subq = (
                session.query(
                    TokenUsage.research_id.label("research_id"),
                    func.max(TokenUsage.model_name).label("model_name"),
                )
                .group_by(TokenUsage.research_id)
                .subquery()
            )

            recent_ratings_query = (
                session.query(
                    ResearchRating.rating,
                    ResearchRating.created_at,
                    ResearchRating.research_id,
                    ResearchHistory.query,
                    ResearchHistory.mode,
                    recent_model_subq.c.model_name,
                    ResearchRating.feedback,
                )
                .outerjoin(
                    ResearchHistory,
                    ResearchRating.research_id == ResearchHistory.id,
                )
                .outerjoin(
                    recent_model_subq,
                    ResearchRating.research_id
                    == recent_model_subq.c.research_id,
                )
            )

            if time_condition is not None:
                recent_ratings_query = recent_ratings_query.filter(
                    time_condition
                )

            recent_ratings = (
                recent_ratings_query.order_by(ResearchRating.created_at.desc())
                .limit(20)
                .all()
            )

            # Recent feedback entries (non-empty feedback text)
            recent_feedback_query = session.query(
                ResearchRating.feedback,
                ResearchRating.rating,
                ResearchRating.created_at,
                ResearchRating.research_id,
            ).filter(
                ResearchRating.feedback.isnot(None),
                ResearchRating.feedback != "",
            )

            if time_condition is not None:
                recent_feedback_query = recent_feedback_query.filter(
                    time_condition
                )

            recent_feedback = (
                recent_feedback_query.order_by(ResearchRating.created_at.desc())
                .limit(20)
                .all()
            )

            return {
                "overall_stats": {
                    "avg_rating": round(overall_stats.avg_rating or 0, 2),
                    "total_ratings": overall_stats.total_ratings or 0,
                    "rating_distribution": {
                        "5": overall_stats.five_star or 0,
                        "4": overall_stats.four_star or 0,
                        "3": overall_stats.three_star or 0,
                        "2": overall_stats.two_star or 0,
                        "1": overall_stats.one_star or 0,
                    },
                },
                "llm_ratings": [
                    {
                        "model": rating.model,
                        "avg_rating": round(rating.avg_rating or 0, 2),
                        "rating_count": rating.rating_count or 0,
                        "positive_ratings": rating.positive_ratings or 0,
                        "neutral_ratings": rating.neutral_ratings or 0,
                        "negative_ratings": rating.negative_ratings or 0,
                        "satisfaction_rate": round(
                            (rating.positive_ratings or 0)
                            / max(rating.rating_count or 1, 1)
                            * 100,
                            1,
                        ),
                    }
                    for rating in llm_ratings
                ],
                "search_engine_ratings": [
                    {
                        "search_engine": rating.search_engine,
                        "avg_rating": round(rating.avg_rating or 0, 2),
                        "rating_count": rating.rating_count or 0,
                        "positive_ratings": rating.positive_ratings or 0,
                        "satisfaction_rate": round(
                            (rating.positive_ratings or 0)
                            / max(rating.rating_count or 1, 1)
                            * 100,
                            1,
                        ),
                    }
                    for rating in search_engine_ratings
                ],
                "rating_trends": [
                    {
                        "date": str(trend.date),
                        "avg_rating": round(trend.avg_rating or 0, 2),
                        "count": trend.daily_count or 0,
                    }
                    for trend in rating_trends
                ],
                "recent_ratings": [
                    {
                        "rating": rating.rating,
                        "created_at": rating.created_at.isoformat()
                        if rating.created_at
                        else None,
                        "research_id": rating.research_id,
                        "query": (
                            rating.query
                            if rating.query
                            else f"Research Session #{rating.research_id}"
                        ),
                        "mode": rating.mode
                        if rating.mode
                        else "Standard Research",
                        "llm_model": (
                            rating.model_name
                            if rating.model_name
                            else "LLM Model"
                        ),
                        "feedback": rating.feedback,
                    }
                    for rating in recent_ratings
                ],
                "mode_ratings": [
                    {
                        "mode": rating.mode,
                        "avg_rating": round(rating.avg_rating or 0, 2),
                        "rating_count": rating.rating_count or 0,
                        "satisfaction_rate": round(
                            (rating.positive_ratings or 0)
                            / max(rating.rating_count or 1, 1)
                            * 100,
                            1,
                        ),
                    }
                    for rating in mode_ratings
                ],
                "quality_dimensions": {
                    "avg_accuracy": round(dimension_stats.avg_accuracy, 2)
                    if dimension_stats.avg_accuracy is not None
                    else None,
                    "avg_completeness": round(
                        dimension_stats.avg_completeness, 2
                    )
                    if dimension_stats.avg_completeness is not None
                    else None,
                    "avg_relevance": round(dimension_stats.avg_relevance, 2)
                    if dimension_stats.avg_relevance is not None
                    else None,
                    "avg_readability": round(dimension_stats.avg_readability, 2)
                    if dimension_stats.avg_readability is not None
                    else None,
                    "dimension_count": dimension_stats.dimension_count or 0,
                    "dimension_counts": {
                        "accuracy": dimension_stats.count_accuracy or 0,
                        "completeness": dimension_stats.count_completeness or 0,
                        "relevance": dimension_stats.count_relevance or 0,
                        "readability": dimension_stats.count_readability or 0,
                    },
                },
                "recent_feedback": [
                    {
                        "feedback": rating.feedback,
                        "rating": rating.rating,
                        "created_at": rating.created_at.isoformat()
                        if rating.created_at
                        else None,
                        "research_id": rating.research_id,
                    }
                    for rating in recent_feedback
                ],
            }

    except Exception:
        logger.exception("Error getting star reviews data")
        return JSONResponse(
            {"error": "An internal error occurred. Please try again later."},
            status_code=500,
        )


@router.get("/api/pricing")
def api_pricing(
    request: Request, username: Annotated[str, Depends(require_auth)]
):
    """Get current LLM pricing data."""
    try:
        from ...metrics.pricing.pricing_fetcher import PricingFetcher

        # Use static pricing data instead of async
        fetcher = PricingFetcher()
        pricing_data = fetcher.static_pricing

        return {
            "status": "success",
            "pricing": pricing_data,
            "last_updated": datetime.now(UTC).isoformat(),
            "note": "Pricing data is from static configuration. Real-time APIs not available for most providers.",
        }

    except Exception:
        logger.exception("Error fetching pricing data")
        return JSONResponse({"error": "Internal Server Error"}, status_code=500)


@router.get("/api/pricing/{model_name}")
def api_model_pricing(
    request: Request,
    model_name,
    username: Annotated[str, Depends(require_auth)],
):
    """Get pricing for a specific model."""
    try:
        # Optional provider parameter
        provider = request.query_params.get("provider")

        from ...metrics.pricing.cost_calculator import CostCalculator

        # Use synchronous approach with cached/static pricing
        calculator = CostCalculator()
        pricing = calculator.calculate_cost_sync(
            model_name, 1000, 1000, provider=provider
        ).get("pricing_used", {})

        return {
            "status": "success",
            "model": model_name,
            "provider": provider,
            "pricing": pricing,
            "last_updated": datetime.now(UTC).isoformat(),
        }

    except Exception as exc:
        logger.opt(exception=False).error(
            "Error getting pricing for model: {} ({})",
            _log_value_preview(model_name),
            type(exc).__name__,
        )
        return JSONResponse(
            {"error": "An internal error occurred"}, status_code=500
        )


@router.post("/api/cost-calculation")
async def api_cost_calculation(
    request: Request, username: Annotated[str, Depends(require_auth)]
):
    """Calculate cost for token usage."""
    # Parse before the broad exception handler so malformed bodies retain
    # this route's validation envelope instead of becoming server errors.
    data, body_error = await read_json_dict(
        request, "simple", "No data provided"
    )
    if body_error is not None:
        return body_error
    try:
        model_name = data.get("model_name")
        provider = data.get("provider")  # Optional provider parameter
        prompt_tokens = data.get("prompt_tokens", 0)
        completion_tokens = data.get("completion_tokens", 0)

        if not model_name:
            return JSONResponse(
                {"error": "model_name is required"}, status_code=400
            )
        if provider is not None and not isinstance(provider, str):
            return JSONResponse(
                {"error": "provider must be a string"}, status_code=400
            )

        from ...metrics.pricing.cost_calculator import CostCalculator
        import asyncio as _asyncio

        # Offload the sync pricing lookup so the event loop isn't blocked
        # waiting on its I/O (pricing table fetch / file read).
        calculator = CostCalculator()
        cost_data = await _asyncio.to_thread(
            calculator.calculate_cost_sync,
            model_name,
            prompt_tokens,
            completion_tokens,
            provider=provider,
        )

        return {
            "status": "success",
            "model_name": model_name,
            "provider": provider,
            "prompt_tokens": prompt_tokens,
            "completion_tokens": completion_tokens,
            "total_tokens": prompt_tokens + completion_tokens,
            **cost_data,
        }

    except Exception:
        logger.exception("Error calculating cost")
        return JSONResponse(
            {"error": "An internal error occurred"}, status_code=500
        )


@router.get("/api/research-costs/{research_id}")
def api_research_costs(
    request: Request,
    research_id,
    username: Annotated[str, Depends(require_auth)],
):
    """Get cost analysis for a specific research session."""
    try:
        from ...metrics.pricing.cost_calculator import (
            CostCalculator,
            summarize_costs,
        )

        with get_user_db_session(username) as session:
            # Get token usage records for this research
            usage_records = (
                session.query(TokenUsage)
                .filter(TokenUsage.research_id == research_id)
                .all()
            )

            if not usage_records:
                return {
                    "status": "success",
                    "research_id": research_id,
                    **summarize_costs([]),
                    "message": "No token usage data found for this research session",
                }

            # Convert to dict format for cost calculation
            usage_data = []
            for record in usage_records:
                usage_data.append(
                    {
                        "model_name": record.model_name,
                        "provider": getattr(
                            record, "model_provider", None
                        ),  # Handle both old and new records
                        "prompt_tokens": record.prompt_tokens,
                        "completion_tokens": record.completion_tokens,
                        "timestamp": record.timestamp,
                    }
                )

            # Use synchronous calculation for research costs
            calculator = CostCalculator()
            costs = []
            for record in usage_data:
                cost_data = calculator.calculate_cost_sync(
                    record["model_name"],
                    record["prompt_tokens"],
                    record["completion_tokens"],
                    provider=record["provider"],
                )
                costs.append({**record, **cost_data})

            return {
                "status": "success",
                "research_id": research_id,
                **summarize_costs(costs),
            }

    except Exception:
        logger.exception(
            f"Error getting research costs for research: {_log_value_preview(research_id)}"
        )
        return JSONResponse(
            {"error": "An internal error occurred"}, status_code=500
        )


@router.get("/api/cost-analytics")
def api_cost_analytics(
    request: Request, username: Annotated[str, Depends(require_auth)]
):
    """Get cost analytics across all research sessions."""
    try:
        from ...metrics.pricing.cost_calculator import (
            CostCalculator,
            summarize_costs,
        )

        period = request.query_params.get("period", "30d")

        with get_user_db_session(username) as session:
            # Get token usage for the period
            query = session.query(TokenUsage)
            time_condition = get_time_filter_condition(
                period, TokenUsage.timestamp
            )
            if time_condition is not None:
                query = query.filter(time_condition)

            # First check if we have any records to avoid expensive queries
            record_count = query.count()

            if record_count == 0:
                return {
                    "status": "success",
                    "period": period,
                    "overview": {
                        **summarize_costs([]),
                        "avg_cost_per_research": 0.0,
                        "total_matching_calls": 0,
                        "usage_truncated": False,
                    },
                    "top_expensive_research": [],
                    "research_count": 0,
                    "message": "No token usage data found for this period",
                }

            # If we have too many records, limit to recent ones to avoid timeout
            if record_count > 1000:
                logger.warning(
                    f"Large dataset detected ({record_count} records), limiting to recent 1000 for performance"
                )
                usage_records = (
                    query.order_by(TokenUsage.timestamp.desc())
                    .limit(1000)
                    .all()
                )
            else:
                usage_records = query.all()

            # Convert to dict format
            usage_data = []
            for record in usage_records:
                usage_data.append(
                    {
                        "model_name": record.model_name,
                        "provider": getattr(
                            record, "model_provider", None
                        ),  # Handle both old and new records
                        "prompt_tokens": record.prompt_tokens,
                        "completion_tokens": record.completion_tokens,
                        "research_id": record.research_id,
                        "timestamp": record.timestamp,
                    }
                )

            # Use synchronous calculation
            calculator = CostCalculator()

            # Calculate overall costs
            costs = []
            for record in usage_data:
                cost_data = calculator.calculate_cost_sync(
                    record["model_name"],
                    record["prompt_tokens"],
                    record["completion_tokens"],
                    provider=record["provider"],
                )
                costs.append({**record, **cost_data})

            cost_summary = summarize_costs(costs)
            cost_summary["total_matching_calls"] = record_count
            cost_summary["usage_truncated"] = record_count > len(costs)

            # Group by research_id for per-research costs
            research_costs: dict[str, Any] = {}
            for record in costs:
                rid = record["research_id"]
                if rid not in research_costs:
                    research_costs[rid] = []
                research_costs[rid].append(record)

            # Calculate cost per research
            research_summaries = {
                rid: summarize_costs(records)
                for rid, records in research_costs.items()
            }
            cost_summary["avg_cost_per_research"] = (
                round(cost_summary["total_cost"] / len(research_summaries), 6)
                if research_summaries
                else 0.0
            )

            # Top expensive research sessions
            top_expensive = sorted(
                research_summaries.items(),
                key=lambda x: x[1]["total_cost"],
                reverse=True,
            )[:10]

            return {
                "status": "success",
                "period": period,
                "overview": cost_summary,
                "top_expensive_research": [
                    {
                        "research_id": rid,
                        "total_cost": data["total_cost"],
                        "pricing_complete": data["pricing_complete"],
                        "unpriced_calls": data["unpriced_calls"],
                        "unpriced_tokens": data["unpriced_tokens"],
                    }
                    for rid, data in top_expensive
                ],
                "research_count": len(research_summaries),
            }

    except Exception:
        logger.exception("Error getting cost analytics")
        # Return a real error so the UI can distinguish "no data" from
        # "this query failed". Returning 200 with status=success masked
        # genuine failures (DB unavailable, schema mismatch).
        return JSONResponse(
            {
                "status": "error",
                "period": period,
                "error": "Cost analytics temporarily unavailable",
            },
            status_code=500,
        )


@router.get("/links")
def link_analytics(
    request: Request, username: Annotated[str, Depends(require_auth)]
):
    """Display link analytics page."""
    return templates.TemplateResponse(
        request=request,
        name="pages/link_analytics.html",
        context={"request": request},
    )


@router.get("/api/link-analytics")
def api_link_analytics(
    request: Request, username: Annotated[str, Depends(require_auth)]
):
    """Get link analytics data."""
    try:
        period = request.query_params.get("period", "30d")

        # Get link analytics data
        link_data = get_link_analytics(period, username)

        return {
            "status": "success",
            "data": link_data["link_analytics"],
            "period": period,
        }

    except Exception:
        logger.exception("Error getting link analytics")
        return JSONResponse(
            {
                "status": "error",
                "message": "An internal error occurred. Please try again later.",
            },
            status_code=500,
        )


@router.get("/api/domain-classifications")
def api_get_domain_classifications(
    request: Request, username: Annotated[str, Depends(require_auth)]
):
    """Get all domain classifications."""
    classifier = None
    try:
        classifier = DomainClassifier(username)
        classifications = classifier.get_all_classifications()

        return {
            "status": "success",
            "classifications": [c.to_dict() for c in classifications],
            "total": len(classifications),
        }

    except Exception:
        logger.exception("Error getting domain classifications")
        return JSONResponse(
            {
                "status": "error",
                "message": "Failed to retrieve classifications",
            },
            status_code=500,
        )
    finally:
        if classifier is not None:
            from ...utilities.resource_utils import safe_close

            safe_close(classifier, "domain classifier")


@router.get("/api/domain-classifications/summary")
def api_get_classifications_summary(
    request: Request, username: Annotated[str, Depends(require_auth)]
):
    """Get summary of domain classifications by category."""
    classifier = None
    try:
        classifier = DomainClassifier(username)
        summary = classifier.get_categories_summary()

        return {"status": "success", "summary": summary}

    except Exception:
        logger.exception("Error getting classifications summary")
        return JSONResponse(
            {"status": "error", "message": "Failed to retrieve summary"},
            status_code=500,
        )
    finally:
        if classifier is not None:
            from ...utilities.resource_utils import safe_close

            safe_close(classifier, "domain classifier")


#: Longest ``domain`` accepted by the classify route. Matches the
#: ``String(255)`` declared on ``DomainClassification.domain`` — SQLite
#: does not enforce column lengths, so without this bound a request-
#: supplied string of any length is interpolated verbatim into the
#: classification prompt, persisted as the classification key, and
#: reflected whole in this route's 400 body. Legitimate values (the
#: authorities the UI extracts from the user's own resource URLs, and
#: the keys the batch path derives) are hostnames with an optional port,
#: well under this bound.
_MAX_DOMAIN_LENGTH = 255


def _domain_rejection_reason(domain: str) -> str | None:
    """Fail-closed length/shape bound on a request-supplied ``domain``.

    Returns a rejection reason for the 400 body, or ``None`` when the
    value may flow on. Control characters never appear in a hostname;
    rejecting them keeps newline/NUL smuggling shapes out of the
    classification prompt, the persisted key and the failure-path echo.
    """
    if len(domain) > _MAX_DOMAIN_LENGTH:
        return f"domain must be at most {_MAX_DOMAIN_LENGTH} characters"
    if any(ord(ch) < 0x20 or ord(ch) == 0x7F for ch in domain):
        return "domain must not contain control characters"
    return None


@router.post("/api/domain-classifications/classify")
async def api_classify_domains(
    request: Request, username: Annotated[str, Depends(require_auth)]
):
    """Trigger classification of a specific domain or batch classification."""
    data, body_error = await read_json_dict(
        request, "status", "Request body must be valid JSON"
    )
    if body_error is not None:
        return body_error
    domain = data.get("domain")
    force_update = data.get("force_update", False)
    batch_mode = data.get("batch", False)
    if domain is not None and not isinstance(domain, str):
        return json_body_error("status", "domain must be a string")
    if not isinstance(force_update, bool):
        return json_body_error("status", "force_update must be a boolean")
    if not isinstance(batch_mode, bool):
        return json_body_error("status", "batch must be a boolean")
    if isinstance(domain, str):
        reason = _domain_rejection_reason(domain)
        if reason is not None:
            return json_body_error("status", reason)

    def _classify_sync():
        """All the sync LLM + DB work — run in a threadpool so we don't
        block the asyncio event loop for seconds per request."""
        from ...settings.manager import SettingsManager
        from ...database.session_context import get_user_db_session
        from ...utilities.resource_utils import safe_close

        classifier = None
        try:
            with get_user_db_session(username) as db_session:
                settings_manager = SettingsManager(db_session=db_session)
                settings_snapshot = settings_manager.get_all_settings()

            classifier = DomainClassifier(
                username, settings_snapshot=settings_snapshot
            )

            if domain and not batch_mode:
                logger.info(
                    "Classifying single domain: {}", _log_value_preview(domain)
                )
                classification = classifier.classify_domain(
                    domain, force_update
                )
                if classification:
                    return {
                        "status": "success",
                        "classification": classification.to_dict(),
                    }
                return JSONResponse(
                    {
                        "status": "error",
                        "message": f"Failed to classify domain: {domain}",
                    },
                    status_code=400,
                )
            if batch_mode:
                logger.info("Starting batch classification of all domains")
                results = classifier.classify_all_domains(force_update)
                return {"status": "success", "results": results}
            return JSONResponse(
                {
                    "status": "error",
                    "message": "Must provide either 'domain' or set 'batch': true",
                },
                status_code=400,
            )
        except Exception:
            logger.exception("Error classifying domains")
            return JSONResponse(
                {"status": "error", "message": "Failed to classify domains"},
                status_code=500,
            )
        finally:
            if classifier is not None:
                safe_close(classifier, "domain classifier")

    return await run_db_sync(_classify_sync)


@router.get("/api/domain-classifications/progress")
def api_classification_progress(
    request: Request, username: Annotated[str, Depends(require_auth)]
):
    """Get progress of domain classification task."""
    try:
        # Get counts of classified vs unclassified domains
        with get_user_db_session(username) as session:
            # Count total unique domains
            resources = session.query(ResearchResource.url).distinct().all()
            domains = set()

            for (url,) in resources:
                if url:
                    domain = _extract_domain(url)
                    if domain:
                        domains.add(domain)

            all_domains = sorted(domains)
            total_domains = len(domains)

            # Count classified domains
            classified_count = session.query(DomainClassification).count()

            return {
                "status": "success",
                "progress": {
                    "total_domains": total_domains,
                    "classified": classified_count,
                    "unclassified": total_domains - classified_count,
                    "percentage": round(
                        (classified_count / total_domains * 100)
                        if total_domains > 0
                        else 0,
                        1,
                    ),
                    "all_domains": all_domains,  # Return all domains for classification
                },
            }

    except Exception:
        logger.exception("Error getting classification progress")
        return JSONResponse(
            {"status": "error", "message": "Failed to retrieve progress"},
            status_code=500,
        )


# ---------------------------------------------------------------------------
# Journal Quality Dashboard
# ---------------------------------------------------------------------------


# Rate-limit constants for the journal-quality endpoints. The old Flask
# decorators (`journal_data_limit`, `journals_read_limit`) lived in
# `security/rate_limiter.py`, which the FastAPI migration removed. We
# re-use slowapi's `limiter.limit()` with the same intent:
# - journal-data download is expensive (~several hundred MB fetch +
#   reference DB rebuild), so cap tightly
# - journal read endpoints are cheap but still worth a per-user rate
#   to blunt enumeration
_JOURNAL_DATA_LIMIT = "2 per hour"
_JOURNALS_READ_LIMIT = "60 per minute"

# SHARED buckets, matching main's journal_data_limit / journals_read_limit
# (security/rate_limiter.py). Using per-endpoint `limiter.limit()` gave each
# of the three read endpoints its OWN 60/min bucket (180/min combined), which
# defeats the anti-enumeration throttle on the ~217K-row reference DB. A
# single scope per group + per-user keying restores the intended combined cap.
_journal_data_limit = limiter.shared_limit(
    _JOURNAL_DATA_LIMIT, scope="journal_data", key_func=_user_key
)
_journals_read_limit = limiter.shared_limit(
    _JOURNALS_READ_LIMIT, scope="journals_read", key_func=_user_key
)


def _resolve_persisted_egress_scope(username: str) -> tuple[Any, Any]:
    """Resolve the user's persisted ``policy.egress_scope``.

    Returns ``(scope, scope_raw)``. ``scope`` is an ``EgressScope``, or
    ``None`` when the stored value cannot be parsed — every caller treats
    that as "fail closed". ``scope_raw`` is the stored value (with the
    retired ``both`` rewritten to ``adaptive``) and exists only for the
    audit log.

    Sync on purpose: it opens the user's SQLCipher settings session, so
    async callers hand it to ``run_db_sync`` instead of the event loop.
    """
    from ...security.egress.policy import (
        DEFAULT_EGRESS_SCOPE,
        EgressScope,
        PolicyDeniedError,
        parse_user_egress_scope,
    )
    from ...utilities.db_utils import get_settings_manager

    scope_raw = get_settings_manager(username=username).get_setting(
        "policy.egress_scope", DEFAULT_EGRESS_SCOPE
    )
    # Retired "both" reads as the adaptive default, mirroring
    # context_from_snapshot's read-time backstop for un-migrated rows.
    if str(scope_raw).strip().lower() == EgressScope.BOTH.value:
        scope_raw = EgressScope.ADAPTIVE.value
    try:
        # Stale "unprotected" rows fall back to adaptive when the
        # operator gate is off, matching every other runtime reader.
        scope = parse_user_egress_scope(
            scope_raw, disabled_unprotected="adaptive"
        )
    except PolicyDeniedError:
        scope = None  # corrupt scope -> callers fail closed
    return scope, scope_raw


def _egress_scope_forbids_public_fetch(scope: Any) -> bool:
    """Whether ``scope`` rules out fetching the public journal datasets.

    ``None`` — an unparseable stored value — fails closed, like every
    other runtime reader of this setting.
    """
    from ...security.egress.policy import EgressScope

    return scope is None or scope in (
        EgressScope.PRIVATE_ONLY,
        EgressScope.STRICT,
    )


def _resolve_effective_egress_scope(username: str) -> Any:
    """Resolve the egress scope a research run for ``username`` would get.

    Unlike ``_resolve_persisted_egress_scope``, which returns the literal
    stored value, this resolves ADAPTIVE against the user's primary
    search engine through ``build_run_egress_context`` — the seam the
    research worker uses to arm a run's context, and the same
    ``context_from_snapshot`` resolution the reputation filter's
    ``_should_skip_journal_fetch_for_scope`` applies. Under the default
    ADAPTIVE scope a private primary (a library/collection engine or a
    per-user private retriever) resolves PRIVATE_ONLY, so a read route
    that only looked at the literal ``adaptive`` would start a public
    download those siblings refuse.

    Raises on any resolution failure (unreadable settings, an unparseable
    scope, no primary engine configured); the caller fails closed.

    Sync on purpose: it opens the user's SQLCipher settings session.
    """
    from ...security.egress.policy import build_run_egress_context
    from ...utilities.db_utils import get_settings_manager

    snapshot = get_settings_manager(username=username).get_settings_snapshot(
        strict=True
    )
    if not isinstance(snapshot, dict):
        raise TypeError(
            f"settings snapshot must be a dict, got {type(snapshot).__name__}"
        )
    primary = snapshot.get("search.tool")
    if isinstance(primary, dict):
        primary = primary.get("value")
    return build_run_egress_context(
        snapshot,
        primary if isinstance(primary, str) else None,
        username=username,
    ).scope


def _journal_ref_db_read_would_download(username: str) -> bool:
    """Whether reading the reference DB would fetch the public datasets.

    ``JournalQualityDB._ensure_engine`` lazily BUILDS the reference DB on
    TWO conditions, not one: when the file is missing, and when an
    existing file fails ``_validate_existing_db`` — which every install
    hits the first time it runs after a ``JOURNAL_QUALITY_SCHEMA_VERSION``
    bump (three have shipped) or after the file is corrupted. That build
    downloads several hundred MB from OpenAlex/DOAJ/GitHub *unless it has
    local snapshots to compile from*. The build's own egress gate reads
    the context armed on the calling thread, but these routes are sync
    handlers that Starlette runs on an anyio threadpool worker where
    nothing arms one — so that gate is a no-op here and a plain dashboard
    page load would start the download.

    The predicate that actually governs the download is therefore the
    SNAPSHOT, not the compiled DB, and this function answers it in that
    order:

    1. ``REQUIRED_SNAPSHOT_FILENAME`` present in the journal data
       directory → ``ensure_journal_data`` reports "available" after one
       stat and the build compiles from disk. Never a download, so never
       blocked, whatever the scope. (A forbidding scope must not turn an
       offline rebuild into a dark dashboard.)
    2. No snapshot, but the compiled DB exists AND passes the same
       validity probe ``_ensure_engine`` applies → no build runs at all,
       so not blocked. The probe is ``journal_db_file_is_valid``, the
       read-only half of ``_validate_existing_db``: it opens the file
       ``mode=ro``, reads ``PRAGMA user_version`` and ``sqlite_master``,
       and — unlike the method — does not unlink an unusable file, so
       asking the question cannot destroy the user's DB or start a build.
    3. Otherwise a read WOULD have to download. Resolve the scope a
       research run for this user would get — ``policy.egress_scope``
       with ADAPTIVE resolved against the user's primary search engine
       (``_resolve_effective_egress_scope``) — so the caller can answer
       "unavailable" rather than fetch. Any resolution failure (corrupt
       scope, no primary engine, unreadable settings) fails closed.

    Only case 3 opens the settings session, and only case 2 opens the
    SQLite file, so the healthy dashboard still costs one stat.
    """
    from ...config.paths import get_journal_data_directory
    from ...journal_quality.db import DB_FILENAME, journal_db_file_is_valid
    from ...journal_quality.downloader import REQUIRED_SNAPSHOT_FILENAME

    try:
        data_dir = get_journal_data_directory()
        if (data_dir / REQUIRED_SNAPSHOT_FILENAME).exists():
            return False
        db_path = data_dir / DB_FILENAME
        if db_path.exists() and journal_db_file_is_valid(db_path):
            return False
    except Exception:
        # Reads fail closed on an unreadable journal data directory. That
        # has not been logged by the time it gets here — `_ensure_dir` mkdirs with `label=None` and logs
        # nothing, and `get_data_directory` raises its `LDR_DATA_DIR`
        # ValueError unlogged — so log it here rather than swallow a
        # misconfigured deployment into a silent 503. Fail closed because
        # this is exactly the case where the fetch cannot be shown to be
        # allowed: the read degrades to "unavailable" instead of starting
        # the download.
        logger.exception(
            "journal reference DB egress pre-check failed; treating the "
            "read as blocked"
        )
        return True
    try:
        scope = _resolve_effective_egress_scope(username)
    except Exception as exc:
        # Fail closed, but WITHOUT a traceback: the frames below hold the
        # user's full settings snapshot (API keys included), which a
        # diagnose-mode traceback would render. Type name only.
        logger.bind(policy_audit=True).warning(
            "journal reference DB egress scope unresolvable "
            f"({type(exc).__name__}); treating the read as blocked"
        )
        return True
    return _egress_scope_forbids_public_fetch(scope)


@router.get("/journals")
def journal_quality(
    request: Request, username: Annotated[str, Depends(require_auth)]
):
    """Display journal quality dashboard."""
    return templates.TemplateResponse(
        request=request,
        name="pages/journal_quality.html",
        context={"request": request},
    )


@router.get("/api/journal-data/status")
def api_journal_data_status(
    request: Request, username: Annotated[str, Depends(require_auth)]
):
    """Get status of downloadable journal data files."""
    try:
        from ...journal_quality.downloader import (
            get_journal_data_status,
        )

        return get_journal_data_status()
    except Exception:
        logger.exception("Error checking journal data status")
        return JSONResponse(
            {"error": "Failed to check status"}, status_code=500
        )


@router.post("/api/journal-data/download")
@_journal_data_limit
async def api_journal_data_download(
    request: Request, username: Annotated[str, Depends(require_auth)]
):
    """Trigger download/update of journal data files.

    Rate-limited to 2 per hour per authenticated user: the download streams
    several hundred MB and rebuilds the on-disk reference DB, so unbounded
    invocation is a DoS vector. The actual download + rebuild runs in a
    worker thread so the uvicorn loop isn't blocked for the minutes this
    may take.
    """
    try:
        from ...journal_quality.downloader import (
            download_journal_data,
            get_download_state,
        )
        from ...journal_quality.data_sources import ALL_SOURCES

        # Egress policy: this endpoint streams several hundred MB over public
        # HTTP. Under an offline-for-public scope (PRIVATE_ONLY / STRICT) the
        # user has opted out of public egress, so refuse rather than reaching
        # out. A corrupt/unknown scope also fails closed. The background
        # auto-download path is already gated by
        # JournalReputationFilter._should_skip_journal_fetch_for_scope; this
        # closes the manual button as the matching entry point.
        # Settings read opens the user's SQLCipher session (sync) — keep it
        # off the event loop. A rekey sidecar or epoch fault on that read
        # raises a RekeyOperationalError rather than reading as "no
        # database", which would answer the default scope instead of the
        # stored one; it is passed on below for the app's retryable 503.
        scope, scope_raw = await run_db_sync(
            lambda: _resolve_persisted_egress_scope(username)
        )
        if _egress_scope_forbids_public_fetch(scope):
            logger.bind(policy_audit=True).warning(
                "journal data download refused by egress policy",
                scope=str(scope_raw),
            )
            return JSONResponse(
                {
                    "success": False,
                    "message": (
                        "Journal data download needs public network "
                        "access, which the current egress policy blocks "
                        "(private/offline scope). Change the egress "
                        "scope to download."
                    ),
                },
                status_code=403,
            )

        # Parse the force flag from the request body if present.
        force = False
        ctype = request.headers.get("content-type", "")
        if "application/json" in ctype:
            try:
                body = await request.json()
            except Exception:
                return JSONResponse(
                    {
                        "success": False,
                        "message": "Request body must be valid JSON",
                    },
                    status_code=400,
                )
            if not isinstance(body, dict):
                return JSONResponse(
                    {
                        "success": False,
                        "message": "Request body must be valid JSON",
                    },
                    status_code=400,
                )
            force = body.get("force", False)
            if not isinstance(force, bool):
                return JSONResponse(
                    {
                        "success": False,
                        "message": "force must be a boolean",
                    },
                    status_code=400,
                )

        # `download_journal_data` already calls `build_reference_db()`
        # + `reset_db()` internally on its success path (downloader.py
        # → db.py); we used to redo it here, but a second rebuild ran
        # the full ~30s pipeline twice and wrote to the legacy
        # `journal_reference.db` filename that the downloader had just
        # cleaned up. See main's #3574 for the simplification.
        def _run_download() -> tuple[bool, str | None]:
            return download_journal_data(force=force)

        success, internal_message = await asyncio.to_thread(_run_download)
        if not success:
            logger.warning(f"Journal data download failed: {internal_message}")
            return {"success": False, "message": "Download failed"}

        # Build the user-facing message locally from structured state
        # (ints + developer-authored source labels). We deliberately do
        # NOT echo `internal_message` from download_journal_data: keeping
        # the response safe-by-construction means a future refactor that
        # lets arbitrary strings (exception info, user input, PII) slip
        # into the downloader's message cannot reach the client.
        counts = get_download_state().get("counts")
        if counts is not None:
            parts = [
                f"{int(counts.get(src.key) or 0)} {src.count_label}"
                for src in ALL_SOURCES
            ]
            user_message = (
                f"Fetched {' + '.join(parts)}. Database rebuilt successfully."
            )
        else:
            # `counts` is None when download_journal_data took its
            # early-return "already up to date" branch (no fetch ran).
            user_message = "Journal data is already up to date."
        return {"success": True, "message": user_message}
    except RekeyOperationalError:
        # The scope could not be read (a rekey sidecar or epoch fault, such
        # as an fd-exhaustion spike after require_auth's probe passed), so
        # nothing was downloaded. Not a server error: the app's handler
        # answers the same retryable 503 + Retry-After as require_auth,
        # and logs only the fault's type name.
        raise
    except Exception:
        logger.exception("Error downloading journal data")
        return JSONResponse(
            {"success": False, "message": "Download failed"},
            status_code=500,
        )


#: Allowlist of ``score_source`` values accepted by ``/api/journals``.
#: Matches the writer side: ``openalex`` / ``doaj`` for reference-DB
#: hits, ``llm`` for Tier 4 cache rows. Empty string means "no filter"
#: and is handled by the caller before validation.
_ALLOWED_SCORE_SOURCES = frozenset({"openalex", "doaj", "llm"})

#: Upper bound on the echoed ``page`` parameter. Prevents a crafted
#: ``?page=10**9`` from issuing an OFFSET scan before the post-query
#: clamp can take effect — reject at input validation instead.
_MAX_PAGE = 10_000


@router.get("/api/journals")
@_journals_read_limit
def api_journal_quality(
    request: Request, username: Annotated[str, Depends(require_auth)]
):
    """Get journal quality data with server-side pagination and filtering.

    Reads from the bundled read-only reference database (~217K journals)
    rather than the per-user DB, so the dashboard is always populated.

    Query params:
        page (int): 1-indexed page number (default 1, max 10000)
        per_page (int): rows per page, max 200 (default 50)
        search (str): name substring filter
        tier (str): elite/strong/moderate/low/predatory
        score_source (str): openalex/doaj/llm (allowlisted)
        sort (str): column to sort by (default quality)
        order (str): asc or desc (default desc)
    """
    try:
        from ...journal_quality.db import get_journal_reference_db

        # Egress policy: ``ref.available`` lazily BUILDS the reference DB
        # when the file is missing OR fails validation, and that build
        # downloads several hundred MB of public data unless the local
        # snapshots are already on disk. Resolve the user's effective
        # scope (ADAPTIVE resolved against the primary engine) FIRST, before anything touches the engine, and answer
        # with the same 503 this route already returns for an
        # unavailable reference DB.
        blocked = _journal_ref_db_read_would_download(username)
        ref = get_journal_reference_db()
        if blocked or not ref.available:
            return JSONResponse(
                {
                    "status": "error",
                    "message": "Journal reference database not available.",
                },
                status_code=503,
            )

        try:
            page = max(1, int(request.query_params.get("page", 1)))
            per_page = min(
                max(1, int(request.query_params.get("per_page", 50))), 200
            )
        except (TypeError, ValueError):
            return JSONResponse(
                {
                    "status": "error",
                    "message": "Invalid pagination parameters",
                },
                status_code=400,
            )
        if page > _MAX_PAGE:
            return JSONResponse(
                {
                    "status": "error",
                    "message": (
                        f"page exceeds maximum ({_MAX_PAGE}); narrow the "
                        "filter or increase per_page"
                    ),
                },
                status_code=400,
            )
        search = request.query_params.get("search", "")
        tier = request.query_params.get("tier", "")
        score_source = request.query_params.get("score_source", "")
        if score_source and score_source not in _ALLOWED_SCORE_SOURCES:
            return JSONResponse(
                {
                    "status": "error",
                    "message": (
                        f"Invalid score_source; must be one of "
                        f"{sorted(_ALLOWED_SCORE_SOURCES)}"
                    ),
                },
                status_code=400,
            )
        sort = request.query_params.get("sort", "quality")
        order = request.query_params.get("order", "desc")

        journals, total = ref.get_journals_page(
            page=page,
            per_page=per_page,
            search=search,
            tier=tier,
            score_source=score_source,
            sort=sort,
            order=order,
        )

        # Clamp the echoed page so the UI never displays out-of-range
        # numbers on crafted input (e.g. ?page=10**9). SQLite's OFFSET on
        # an indexed ORDER BY caps work at ~total rows regardless of the
        # requested offset, so no DB-level clamp is needed.
        total_pages = -(-total // per_page) if per_page > 0 and total > 0 else 1
        page = min(page, total_pages)

        result = {
            "status": "success",
            "journals": journals,
            "pagination": {
                "page": page,
                "per_page": per_page,
                "total_count": total,
                "total_pages": total_pages,
            },
        }

        # Include summary only when requested (avoids 3 extra SQL queries
        # on every pagination/sort/filter request)
        if request.query_params.get("include_summary", "false") == "true":
            summary = ref.get_summary()
            summary["quality_distribution"] = ref.get_quality_distribution()
            summary["source_distribution"] = ref.get_source_distribution()
            result["summary"] = summary

        return result

    except Exception:
        logger.exception("Error getting journal quality data")
        return JSONResponse(
            {
                "status": "error",
                "message": "An internal error occurred. Please try again later.",
            },
            status_code=500,
        )


def _ref_db_lookup(ref_db, name: str) -> dict:
    """Look up a journal's display bibliometrics in the reference DB.

    Returns a dict with keys the dashboard template already renders
    (h_index, impact_factor, sjr_quartile, publisher, is_predatory,
    predatory_source, is_in_doaj). Missing fields default
    to None / False so the frontend never sees KeyError. On any ref-DB
    error the function returns an empty dict — the dashboard still shows
    the name + user-DB quality, just without the extras.
    """
    if ref_db is None or not name:
        return {}
    try:
        entry = ref_db.lookup_source(name=name) or {}
    except Exception:  # allow: silent-exception
        # Reference DB lookups are best-effort enrichment. Any failure
        # degrades to "no bibliometric extras" without crashing the
        # dashboard; detailed errors already surface via the DB layer's
        # own logger.exception calls when they matter.
        return {}
    # lookup_source returns a compact dict; the sjr_quartile lives under
    # "quartile" and predatory/DOAJ fields may be absent entirely.
    return {
        "h_index": entry.get("h_index"),
        "impact_factor": entry.get("impact_factor"),
        "sjr_quartile": entry.get("quartile"),
        "is_predatory": bool(entry.get("is_predatory")),
        "predatory_source": entry.get("predatory_source"),
        "is_in_doaj": bool(entry.get("is_in_doaj")),
        "publisher": entry.get("publisher"),
    }


def _get_ref_db_or_none():
    """Return the JournalQualityDB singleton, or None if unavailable.

    The reference DB is optional — if the user hasn't downloaded the
    snapshot, the dashboard still renders with user-DB data only.
    """
    try:
        from ...journal_quality.db import get_journal_reference_db

        return get_journal_reference_db()
    except Exception:  # allow: silent-exception
        # Reference DB is optional; if import or initialization fails
        # (unusual: usually it's lazily built on first access), the
        # dashboard falls back to user-DB-only rendering.
        return None


def _resolve_paper_quality(
    llm_quality: int | None, enrichment: dict
) -> tuple[int | None, str | None]:
    """Pick a quality score for a dashboard row.

    Precedence: current LLM verdict from the user's ``journals`` table
    (Tier 4 cache, keyed by NFKC-normalized container_title) → live
    derivation from the bundled reference DB row (Tier 1-3). Always
    live — no frozen per-Paper copy exists, so a re-scored journal
    propagates automatically. Returns (score, source_label) or
    (None, None) if neither path had data.
    """
    if llm_quality is not None:
        return llm_quality, "llm"
    if not enrichment:
        return None, None
    # enrichment comes from _source_to_dashboard_dict — row.quality is
    # the ref-DB's pre-computed score (same formula as the filter uses),
    # so we trust it directly rather than re-running derive_quality_score.
    q = enrichment.get("quality")
    if q is not None:
        return int(q), enrichment.get("score_source") or "openalex"
    return None, None


def _lookup_journal_llm_quality(
    db, container_titles: list[str]
) -> dict[str, int]:
    """Batch-look up current Tier 4 LLM verdicts from the user's
    ``journals`` table.

    Returns a dict mapping ``normalize_name(container_title)`` →
    ``Journal.quality``. Missing journals (never Tier-4-scored) simply
    don't appear in the result — callers fall through to the bundled
    reference DB. One indexed ``name_lower IN (...)`` query.
    """
    from ...journal_quality.scoring import normalize_name

    if not container_titles:
        return {}
    normalized = list({normalize_name(ct) for ct in container_titles if ct})
    if not normalized:
        return {}
    rows = (
        db.query(Journal.name_lower, Journal.quality)
        .filter(Journal.name_lower.in_(normalized))
        .filter(Journal.quality.isnot(None))
        .all()
    )
    return {name_lower: int(q) for name_lower, q in rows}


@router.get("/api/journals/user-research")
@_journals_read_limit
def api_user_research_journals(
    request: Request, username: Annotated[str, Depends(require_auth)]
):
    """Get journals from the user's own research sessions.

    Paper-rooted query: groups by ``Paper.container_title`` (the
    cleaned name the filter used to score the journal), counts paper
    appearances. Quality is resolved live — Tier 4 via a batch lookup
    against the user's ``journals`` table (keyed by NFKC-normalized
    container_title), Tier 1-3 via the bundled read-only reference DB.
    A re-scored journal propagates to existing research rows
    automatically because no per-Paper score is stored.
    """
    # `reference_data_available` distinguishes "no predatory journals
    # found" from "predatory journals were never checked for". The
    # reference DB can be withheld from this route entirely — an egress
    # scope that forbids the public fetch, or a build/open failure — and
    # `predatory_blocked: 0` alongside `status: success` would otherwise
    # read as a clean bill of health. The route's own comment on the
    # `predatory_blocked` query calls silently undercounting predatory
    # journals a no-fallbacks violation; this is the same undercount at
    # the response level, so it is flagged rather than hidden. It is
    # False on this early-return shape because every branch that reaches
    # it (no papers table, no rows) returns before the reference DB is
    # consulted: there is nothing to have checked.
    _empty_response = {
        "status": "success",
        "reference_data_available": False,
        "summary": {
            "total_journals": 0,
            "avg_quality": None,
            "total_papers": 0,
            "predatory_blocked": 0,
        },
        "quality_distribution": {},
        "journals": [],
    }

    try:
        from sqlalchemy import inspect as sa_inspect

        with get_user_db_session(username) as db:
            inspector = sa_inspect(db.bind)
            if not inspector.has_table("papers"):
                return _empty_response

            # Top-200 most-cited journals in this user's research.
            # Orphan Papers (whose ``PaperAppearance`` rows were
            # cascade-deleted when their research session was deleted)
            # are excluded so the dashboard reflects what the user
            # currently has, not residual rows from deleted sessions.
            # See issue #3544.
            rows = (
                db.query(
                    Paper.container_title,
                    func.count(Paper.id).label("paper_count"),
                    func.min(Paper.year).label("year_min"),
                    func.max(Paper.year).label("year_max"),
                )
                .filter(Paper.container_title.isnot(None))
                .filter(Paper.appearances.any())
                .group_by(Paper.container_title)
                .order_by(func.count(Paper.id).desc())
                .limit(200)
                .all()
            )

            if not rows:
                return _empty_response

            # One batched ref-DB lookup for the whole top-200 slice —
            # hits `sources.name_lower IN (…)` rather than 200 point
            # queries.
            # Egress policy: every reference-DB read below lazily BUILDS
            # the DB when the file is missing or fails validation, and
            # with no local snapshots that build downloads several
            # hundred MB of public data on a threadpool worker where the
            # build's own scope gate is blind (see
            # _journal_ref_db_read_would_download). Under a forbidding
            # effective scope, degrade to the enrichment-free response
            # this route already returns when the reference DB is
            # unavailable.
            ref_db = (
                None
                if _journal_ref_db_read_would_download(username)
                else _get_ref_db_or_none()
            )
            # `_get_ref_db_or_none` hands back the singleton without
            # opening anything, and the lookups below swallow a failed
            # lazy build/open (FileNotFoundError) into an empty result —
            # so a non-None handle alone would report "checked, none
            # found" for a DB that was never read. `available` runs the
            # same lazy open the lookups run (the egress gate above has
            # already ruled out a forbidden download) and is False on
            # exactly the failure they swallow; drop the handle then.
            if ref_db is not None and not ref_db.available:
                ref_db = None
            enrich_map = {}
            if ref_db is not None:
                enrich_map = ref_db.lookup_sources_batch(
                    [r.container_title for r in rows]
                )

            from ...journal_quality.scoring import normalize_name

            # Batch-look up current LLM verdicts (Tier 4) from the
            # user's journals table, keyed by NFKC-normalized name.
            # Always live — no frozen Paper copy — so a re-scored
            # journal propagates here without any backfill.
            llm_by_name = _lookup_journal_llm_quality(
                db, [r.container_title for r in rows]
            )

            journals: list[dict] = []
            qualities: list[int] = []
            for r in rows:
                normalized = normalize_name(r.container_title)
                enrichment = enrich_map.get(normalized, {})
                quality, source_label = _resolve_paper_quality(
                    llm_by_name.get(normalized), enrichment
                )
                if quality is not None:
                    qualities.append(quality)
                journals.append(
                    {
                        "name": r.container_title,
                        "quality": quality,
                        "score_source": source_label,
                        "paper_count": r.paper_count,
                        "year_min": r.year_min,
                        "year_max": r.year_max,
                        **{
                            k: v
                            for k, v in enrichment.items()
                            if k not in ("quality", "score_source", "name")
                        },
                    }
                )

            # Aggregate stats computed across the top-200 slice for the
            # dashboard summary — matches how the table renders.
            total_journals = len(journals)
            total_papers = sum(r.paper_count for r in rows)
            avg_quality = (
                round(sum(qualities) / len(qualities), 1) if qualities else None
            )
            quality_distribution: dict[str, int] = {}
            for q in qualities:
                quality_distribution[str(q)] = (
                    quality_distribution.get(str(q), 0) + 1
                )

            # Predatory count uses the full set of distinct
            # container_titles across the user's research, not just the
            # top-200 display slice. One batched query.
            #
            # KNOWN-DEFERRED: unbounded SELECT DISTINCT. Acceptable today
            # because typical users have <5K distinct titles even after
            # years of use, and count_predatory_by_names documents
            # support up to ~100K params. Adding .limit(N) was considered
            # and rejected — it would SILENTLY UNDERCOUNT predatory
            # journals, which violates the no-fallbacks rule. Proper fix
            # (cross-DB correlated subquery or TTL cache) is tracked as
            # a post-merge follow-up. Threshold for visible impact:
            # ~50K papers.
            predatory_blocked = 0
            if ref_db is not None:
                # Same orphan-exclusion as the top-200 query above —
                # otherwise predatory_blocked stays inflated by titles
                # whose only Papers belong to deleted research sessions.
                all_names = [
                    name
                    for (name,) in db.query(Paper.container_title)
                    .filter(Paper.container_title.isnot(None))
                    .filter(Paper.appearances.any())
                    .distinct()
                    .all()
                ]
                predatory_blocked = ref_db.count_predatory_by_names(all_names)

        return {
            "status": "success",
            # False whenever `ref_db` was None — the egress gate withheld
            # it, `_get_ref_db_or_none` failed, or the reference DB could
            # not be opened/built (`available` False). Then
            # `predatory_blocked` is 0 because nothing was checked, not
            # because nothing was found, and every bibliometric field on
            # every journal row is absent for the same reason.
            "reference_data_available": ref_db is not None,
            "summary": {
                "total_journals": total_journals,
                "avg_quality": avg_quality,
                "total_papers": total_papers,
                "predatory_blocked": predatory_blocked,
            },
            "quality_distribution": quality_distribution,
            "journals": journals,
        }
    except Exception:
        logger.exception("Error getting user research journals")
        return JSONResponse(
            {
                "status": "error",
                "message": "Failed to load your research data.",
            },
            status_code=500,
        )


@router.get("/api/journals/research/{research_id}")
@_journals_read_limit
def api_research_journals(
    request: Request,
    research_id: str,
    username: Annotated[str, Depends(require_auth)],
):
    """Get journals encountered in a single research session.

    Filters the per-user papers table by joining through
    Paper → PaperAppearance → ResearchResource and matching ``research_id``.
    Quality is resolved live (journals.quality + bundled reference DB)
    so results always reflect the current verdict, not a stale snapshot.
    Mirrors the response shape of /api/journals/user-research so the
    dashboard can reuse its rendering code.
    """
    # `reference_data_available` distinguishes "no predatory journals
    # found" from "predatory journals were never checked for". The
    # reference DB can be withheld from this route entirely — an egress
    # scope that forbids the public fetch, or a build/open failure — and
    # `predatory_blocked: 0` alongside `status: success` would otherwise
    # read as a clean bill of health. The route's own comment on the
    # `predatory_blocked` query calls silently undercounting predatory
    # journals a no-fallbacks violation; this is the same undercount at
    # the response level, so it is flagged rather than hidden. It is
    # False on this early-return shape because every branch that reaches
    # it (no papers table, no rows) returns before the reference DB is
    # consulted: there is nothing to have checked.
    _empty_response = {
        "status": "success",
        "reference_data_available": False,
        "summary": {
            "total_journals": 0,
            "avg_quality": None,
            "total_papers": 0,
            "predatory_blocked": 0,
        },
        "quality_distribution": {},
        "journals": [],
    }

    try:
        from sqlalchemy import inspect as sa_inspect

        with get_user_db_session(username) as db:
            inspector = sa_inspect(db.bind)
            if not inspector.has_table("papers") or not inspector.has_table(
                "paper_appearances"
            ):
                return _empty_response

            # Verify the research_id belongs to this user before exposing
            # any data — research_history is in the same per-user DB so
            # the existence check doubles as an ownership check.
            from ...database.models.research import ResearchHistory

            research = (
                db.query(ResearchHistory.id)
                .filter(ResearchHistory.id == research_id)
                .first()
            )
            if research is None:
                return JSONResponse(
                    {"status": "error", "message": "Research not found"},
                    status_code=404,
                )

            # Aggregate container_title → paper_count for this research.
            # Join chain: Paper → PaperAppearance → ResearchResource.
            rows = (
                db.query(
                    Paper.container_title,
                    func.count(Paper.id).label("paper_count"),
                    func.min(Paper.year).label("year_min"),
                    func.max(Paper.year).label("year_max"),
                )
                .join(
                    PaperAppearance,
                    PaperAppearance.paper_id == Paper.id,
                )
                .join(
                    ResearchResource,
                    ResearchResource.id == PaperAppearance.resource_id,
                )
                .filter(
                    ResearchResource.research_id == research_id,
                    Paper.container_title.isnot(None),
                )
                .group_by(Paper.container_title)
                .order_by(func.count(Paper.id).desc())
                .all()
            )

            if not rows:
                return _empty_response

            # Egress policy: every reference-DB read below lazily BUILDS
            # the DB when the file is missing or fails validation, and
            # with no local snapshots that build downloads several
            # hundred MB of public data on a threadpool worker where the
            # build's own scope gate is blind (see
            # _journal_ref_db_read_would_download). Under a forbidding
            # effective scope, degrade to the enrichment-free response
            # this route already returns when the reference DB is
            # unavailable.
            ref_db = (
                None
                if _journal_ref_db_read_would_download(username)
                else _get_ref_db_or_none()
            )
            # `_get_ref_db_or_none` hands back the singleton without
            # opening anything, and the lookups below swallow a failed
            # lazy build/open (FileNotFoundError) into an empty result —
            # so a non-None handle alone would report "checked, none
            # found" for a DB that was never read. `available` runs the
            # same lazy open the lookups run (the egress gate above has
            # already ruled out a forbidden download) and is False on
            # exactly the failure they swallow; drop the handle then.
            if ref_db is not None and not ref_db.available:
                ref_db = None
            enrich_map = {}
            if ref_db is not None:
                enrich_map = ref_db.lookup_sources_batch(
                    [r.container_title for r in rows]
                )

            from ...journal_quality.scoring import normalize_name

            # Batch-look up current LLM verdicts (Tier 4) — see
            # _lookup_journal_llm_quality for rationale. Same live
            # resolution as the cross-research rollup above.
            llm_by_name = _lookup_journal_llm_quality(
                db, [r.container_title for r in rows]
            )

            journals: list[dict] = []
            qualities: list[int] = []
            predatory_blocked = 0
            for r in rows:
                normalized = normalize_name(r.container_title)
                enrichment = enrich_map.get(normalized, {})
                if enrichment.get("is_predatory"):
                    predatory_blocked += 1
                quality, source_label = _resolve_paper_quality(
                    llm_by_name.get(normalized), enrichment
                )
                if quality is not None:
                    qualities.append(quality)
                journals.append(
                    {
                        "name": r.container_title,
                        "quality": quality,
                        "score_source": source_label,
                        "paper_count": r.paper_count,
                        "year_min": r.year_min,
                        "year_max": r.year_max,
                        **{
                            k: v
                            for k, v in enrichment.items()
                            if k not in ("quality", "score_source", "name")
                        },
                    }
                )

            total_papers = sum(r.paper_count for r in rows)
            avg_quality = (
                round(sum(qualities) / len(qualities), 1) if qualities else None
            )
            quality_distribution: dict[str, int] = {}
            for q in qualities:
                quality_distribution[str(q)] = (
                    quality_distribution.get(str(q), 0) + 1
                )

        return {
            "status": "success",
            # Same marker as /api/journals/user-research, whose response
            # shape this route deliberately mirrors: False means
            # `predatory_blocked` counts nothing because the reference DB
            # was never consulted, not because this research session is
            # clean.
            "reference_data_available": ref_db is not None,
            "summary": {
                "total_journals": len(journals),
                "avg_quality": avg_quality,
                "total_papers": total_papers,
                "predatory_blocked": predatory_blocked,
            },
            "quality_distribution": quality_distribution,
            "journals": journals,
        }
    except Exception:
        logger.exception("Error getting per-research journals")
        return JSONResponse(
            {
                "status": "error",
                "message": "Failed to load research journals.",
            },
            status_code=500,
        )