"""Логирование retrieval/pipeline/ranking для doc-explain find-files."""

from __future__ import annotations

from app.core.agent.utils.process_v2.models import V2RouteResult
from app.core.agent.utils.process_v2.rag_retrieval.target_doc_seeding import normalize_doc_path, row_path


def log_pipeline_step(runtime, step: str, payload: dict[str, object]) -> None:
    runtime.trace.module("process.v2.pipeline").log(step, payload)


def log_retrieval_trace(runtime, route: V2RouteResult, plan, retrieved_rows: list[dict], metadata_rows: list[dict], rows: list[dict]) -> None:
    runtime.trace.module("process.v2.rag_retrieval").log(
        "rag_rows_fetched",
        {
            "profile": plan.profile,
            "row_count": len(rows),
            "rows": [trace_row(row) for row in rows],
        },
    )
    hinted_paths = {normalize_doc_path(hint) for hint in route.anchors.target_doc_hints if str(hint or "").strip()}
    log_pipeline_step(
        runtime,
        "candidate_generation",
        {
            "query": route.user_query,
            "profile": plan.profile,
            "details": {
                "target_doc_hints": list(route.anchors.target_doc_hints),
                "candidates_before_ranking": [row_path(row) for row in rows if row_path(row)],
            },
            "resolved_aliases": route.anchors.matched_aliases,
            "target_doc_hints": route.anchors.target_doc_hints,
            "candidate_docs_before_ranking": [trace_row(row) for row in rows[:8]],
            "sources": {
                "seeded": [trace_row(row) for row in retrieved_rows[:5] if row_path(row) in hinted_paths],
                "metadata_lookup": [trace_row(row) for row in metadata_rows[:5]],
                "semantic": [trace_row(row) for row in retrieved_rows[:5]],
            },
        },
    )
    log_pipeline_step(
        runtime,
        "retrieval_executed",
        {
            "query": route.user_query,
            "profile": plan.profile,
            "row_count": len(rows),
            "target_doc_hints": route.anchors.target_doc_hints,
            "top_results": [trace_row(row) for row in rows[:5]],
        },
    )


def log_ranking(runtime, items: list) -> None:
    top_docs: list[dict[str, object]] = []
    for item in items[:4]:
        top_docs.append(
            {
                "doc": getattr(item, "path", ""),
                "score": getattr(item, "score", 0),
                "match_reason": getattr(item, "match_reason", ""),
            }
        )
        log_pipeline_step(
            runtime,
            "ranking_explained",
            {
                "doc": getattr(item, "path", ""),
                "score_breakdown": getattr(item, "score_breakdown", {}),
                "score": getattr(item, "score", 0),
                "match_reason": getattr(item, "match_reason", ""),
            },
        )
    log_pipeline_step(
        runtime,
        "ranking_explained",
        {
            "top_docs_after_ranking": top_docs,
            "ranking_score_breakdown": [
                {
                    "doc": getattr(item, "path", ""),
                    "score_breakdown": getattr(item, "score_breakdown", {}),
                }
                for item in items[:4]
            ],
        },
    )


def trace_row(row: dict) -> dict[str, object]:
    metadata = row.get("metadata") or {}
    content = str(row.get("content") or "").strip()
    return {
        "layer": str(row.get("layer") or ""),
        "path": str(row.get("path") or ""),
        "title": str(row.get("title") or ""),
        "document_id": str(metadata.get("document_id") or metadata.get("doc_id") or row.get("document_id") or ""),
        "entity_name": str(metadata.get("entity_name") or ""),
        "summary_text": str(metadata.get("summary_text") or "")[:400],
        "section_path": str(metadata.get("section_path") or ""),
        "metadata_domain": str(metadata.get("domain") or ""),
        "metadata_subdomain": str(metadata.get("subdomain") or ""),
        "content_preview": content[:400],
    }
