"""Company / security endpoints — the Company Page (spec §36).

AUDIT NOTE (StockLab overhaul, final engineering pass, Part A3, docs/AUDIT_SECURITY_A3.md):
deliberately left WITHOUT rate limiting, a reasoned decision, not an oversight. Both routes here
are: (a) bounded to a fixed, small number of queries per call regardless of caller input (a single
ticker lookup, no caller-controlled filter/complexity the way screener/search have), and (b) the
highest-legitimate-traffic read path in the whole app -- every search result click, every screener
row click, and the Dashboard all route through here. Rate limiting the single most common
legitimate read path, when it carries none of the unbounded-cost risk the screener/search routes
do, would trade real UX friction for no real risk reduction -- exactly what this pass's "don't
mechanically decorate every endpoint" instruction warns against.
"""

from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy import select
from sqlalchemy.orm import Session

from app.api.v1.serializers import build_company_page, security_eager_load_options
from app.core.db import get_db
from app.models import Metric, Score, Security, Valuation
from app.schemas.common import CompanyPageOut

router = APIRouter(prefix="/v1/companies", tags=["companies"])


@router.get("/{ticker}", response_model=CompanyPageOut)
def get_company_page(ticker: str, db: Session = Depends(get_db)):
    # AUDIT FIX (StockLab overhaul, Part A2): a single page load only ever costs 4 extra lazy-load
    # queries here (not O(N) like the screener/rankings/watchlist list views), but there's no
    # reason to pay even that when selectinload makes it one extra query total -- same helper as
    # the list views, applied consistently per this pass's "ALL call sites" instruction.
    security = db.query(Security).options(*security_eager_load_options()).filter(Security.ticker == ticker.upper()).first()
    if security is None:
        raise HTTPException(404, f"No security found for ticker {ticker}")

    score = db.execute(
        select(Score).where(Score.security_id == security.id).order_by(Score.calculation_date.desc()).limit(1)
    ).scalar_one_or_none()
    val = db.execute(
        select(Valuation).where(Valuation.security_id == security.id).order_by(Valuation.calculation_date.desc()).limit(1)
    ).scalar_one_or_none()
    metrics = db.execute(select(Metric).where(Metric.security_id == security.id)).scalars().all()

    return build_company_page(db, security, score, val, metrics)


@router.get("/{ticker}/metrics", response_model=list)
def get_company_metrics(ticker: str, db: Session = Depends(get_db)):
    """Full 30-metric breakdown (progressive disclosure drill-through, spec §48)."""
    security = db.query(Security).filter(Security.ticker == ticker.upper()).first()
    if security is None:
        raise HTTPException(404, f"No security found for ticker {ticker}")
    metrics = db.execute(select(Metric).where(Metric.security_id == security.id)).scalars().all()
    return [
        {"key": m.metric_key, "value": m.value, "status": m.status, "applicability": m.applicability,
         "formula_version": m.formula_version, "inputs_used": m.inputs_used, "note": m.note, "as_of": m.as_of}
        for m in metrics
    ]
