from __future__ import annotations

from app.core.agent.utils.process_v2.models import V2AnchorType, V2RouteAnchors, V2RouteResult, V2Subintent


def anchor_signal_types(route: V2RouteResult) -> set[str]:
    texts = _signal_texts(route)
    signals: set[str] = set()
    if route.subintent == V2Subintent.FIND_FILES:
        signals.add(V2AnchorType.FIND_FILES)
    if route.anchors.endpoint_paths or _has_any(texts, ("/api/", "api", "endpoint")):
        signals.add(V2AnchorType.API_ENDPOINT)
    if _has_any(texts, ("/architecture/", "architecture", "arch")):
        signals.add(V2AnchorType.ARCHITECTURE)
    if _has_any(texts, ("/logic/", "logic", "workflow", "flow", "process")):
        signals.add(V2AnchorType.LOGIC_FLOW)
    if route.anchors.entity_names or _has_any(texts, ("/domains/", "domain", "entity", "component")):
        signals.add(V2AnchorType.DOMAIN_ENTITY)
    return signals


def route_anchor_summary(route: V2RouteResult) -> dict[str, object]:
    return {
        "entity_names": list(route.anchors.entity_names),
        "file_names": list(route.anchors.file_names),
        "endpoint_paths": list(route.anchors.endpoint_paths),
        "target_doc_hints": list(route.anchors.target_doc_hints),
        "matched_aliases": list(route.anchors.matched_aliases),
        "process_domain": route.anchors.process_domain,
        "process_subdomain": route.anchors.process_subdomain,
        "scope_type": route.scope_type,
        "candidate_domains": [c.value for c in route.anchors.candidate_domains],
        "candidate_subdomains": [c.value for c in route.anchors.candidate_subdomains],
        "candidate_entities": [c.value for c in route.anchors.candidate_entities],
        "candidate_apis": [c.value for c in route.anchors.candidate_apis],
        "signal_types": sorted(anchor_signal_types(route)),
    }


def anchors_have_signal(anchors: V2RouteAnchors, signal: str, *, subintent: str | None = None) -> bool:
    route = V2RouteResult(
        routing_domain="",
        intent="",
        subintent=subintent or "",
        user_query="",
        normalized_query="",
        anchors=anchors,
    )
    return signal in anchor_signal_types(route)


def _signal_texts(route: V2RouteResult) -> list[str]:
    items = [
        *route.anchors.target_doc_hints,
        *route.anchors.file_names,
        *route.anchors.matched_aliases,
    ]
    return [str(item).strip().lower() for item in items if str(item or "").strip()]


def _has_any(items: list[str], markers: tuple[str, ...]) -> bool:
    return any(marker in item for item in items for marker in markers)
