from __future__ import annotations

from typing import Any

DEFAULT_LIQUID_ENTRY_PATH = "Service.Chat/Inference/Prompts/Templates/syndication-api/responding/prompt.liquid"


def normalize_liquid_prompt_entries(
    liquid_prompt_entries: list[Any] | None,
) -> list[dict[str, Any]] | None:
    """
    Normalize liquid prompt entries to a stable schema.

    Normalized entry fields:
    - path (required, non-empty)
    - analyze_structure (optional input, default True)
    - can_edit (optional pass-through)
    """
    if not isinstance(liquid_prompt_entries, list) or not liquid_prompt_entries:
        return None

    normalized: list[dict[str, Any]] = []
    seen_paths: set[str] = set()

    for item in liquid_prompt_entries:
        if hasattr(item, "model_dump") and callable(getattr(item, "model_dump")):
            item = item.model_dump()
        if not isinstance(item, dict):
            continue

        path_raw = item.get("path")
        path = str(path_raw).strip().rstrip(".") if path_raw is not None else ""
        path = path.replace("\\", "/")
        if not path:
            continue
        if path in seen_paths:
            continue
        seen_paths.add(path)

        entry: dict[str, Any] = {
            "path": path,
            "analyze_structure": bool(item.get("analyze_structure", True)),
        }
        if "can_edit" in item:
            entry["can_edit"] = bool(item.get("can_edit", True))
        normalized.append(entry)

    return normalized or None


def resolve_liquid_prompt_entries(
    liquid_prompt_entries: list[Any] | None,
    *,
    legacy_liquid_prompt_file_path: str | None = None,
    default_path: str | None = None,
) -> list[dict[str, Any]]:
    """
    Resolve entries with priority:
    1) Explicit liquid_prompt_entries (normalized)
    2) Legacy liquid_prompt_file_path
    3) default_path (if provided)
    """
    normalized = normalize_liquid_prompt_entries(liquid_prompt_entries)
    if normalized:
        return normalized

    legacy_path = (legacy_liquid_prompt_file_path or "").strip()
    if legacy_path:
        return [{"path": legacy_path, "analyze_structure": True}]

    fallback_path = (default_path or "").strip()
    if fallback_path:
        return [{"path": fallback_path, "analyze_structure": True}]

    return []

