"""Prompt management — Langfuse prompt sync and bootstrap."""
from __future__ import annotations

import os
from typing import Any

from src.langfuse_client import build_langfuse_client
from src.prompts import DEFAULT_PROMPTS


def _prompt_name(key: str) -> str:
    prefix = os.getenv("AGENT_LANGFUSE_PROMPT_PREFIX", "langfuse-lens").strip() or "langfuse-lens"
    normalized = key.replace("_", "-")
    return f"{prefix}.{normalized}"


def _is_not_found_error(exc: Exception) -> bool:
    cls = exc.__class__.__name__.lower()
    msg = str(exc).lower()
    return "notfound" in cls or "not found" in msg or "404" in msg


def _langfuse_prompt_tags() -> list[str]:
    configured = [item.strip() for item in str(os.getenv("AGENT_LANGFUSE_PROMPT_TAGS", "")).strip().split(",") if item.strip()]
    if configured:
        return configured
    return ["langfuse-lens-agent", "deep-agent"]


def _env_bool(name: str, default: bool = False) -> bool:
    raw = os.getenv(name, "").strip().lower()
    if not raw:
        return default
    return raw in {"1", "true", "yes", "y", "on"}


def _env_int(name: str, default: int) -> int:
    raw = os.getenv(name, "").strip()
    if not raw:
        return default
    try:
        return int(raw)
    except Exception:
        return default


def _build_langfuse_prompt_client():
    public_key = os.getenv("LANGFUSE_PUBLIC_KEY", "").strip()
    secret_key = os.getenv("LANGFUSE_SECRET_KEY", "").strip()
    base_url = os.getenv("LANGFUSE_BASE_URL", "").strip()
    environment = os.getenv("LANGFUSE_ENVIRONMENT", "").strip()
    if not (public_key and secret_key and base_url):
        return None, "missing LANGFUSE_BASE_URL/LANGFUSE_PUBLIC_KEY/LANGFUSE_SECRET_KEY"
    timeout = _env_int("AGENT_LANGFUSE_HTTP_TIMEOUT_SEC", 30)
    client, _backend, error = build_langfuse_client(
        public_key=public_key,
        secret_key=secret_key,
        host=base_url,
        environment=environment,
        timeout_sec=max(3, timeout),
    )
    if client is None:
        return None, f"langfuse client init failed: {error}"
    return client, None


def _get_or_create_langfuse_prompt_text(client: Any, prompt_name: str, default_prompt: str) -> str:
    label = os.getenv("AGENT_LANGFUSE_PROMPT_LABEL", "latest").strip() or "latest"
    cache_ttl = max(0, _env_int("AGENT_LANGFUSE_PROMPT_CACHE_TTL_SEC", 60))

    try:
        prompt_obj = client.get_prompt(
            prompt_name,
            label=label,
            type="text",
            cache_ttl_seconds=cache_ttl,
        )
        text = str(getattr(prompt_obj, "prompt", "")).strip()
        if text:
            return text
    except Exception as exc:
        if not _is_not_found_error(exc):
            try:
                prompt_obj = client.get_prompt(
                    prompt_name,
                    label="production",
                    type="text",
                    cache_ttl_seconds=cache_ttl,
                )
                text = str(getattr(prompt_obj, "prompt", "")).strip()
                if text:
                    return text
            except Exception:
                pass

    try:
        created = client.create_prompt(
            name=prompt_name,
            prompt=default_prompt,
            type="text",
            labels=["production"],
            tags=_langfuse_prompt_tags(),
            commit_message="bootstrap default prompt from langfuse-lens-agent",
        )
        created_text = str(getattr(created, "prompt", "")).strip()
        return created_text or default_prompt
    except Exception:
        return default_prompt


def _resolve_prompt_bundle() -> dict[str, str]:
    prompts = dict(DEFAULT_PROMPTS)
    if not _env_bool("AGENT_LANGFUSE_PROMPT_SYNC", default=True):
        return prompts
    client, _error = _build_langfuse_prompt_client()
    if client is None:
        return prompts
    resolved: dict[str, str] = {}
    for key, default_prompt in DEFAULT_PROMPTS.items():
        resolved[key] = _get_or_create_langfuse_prompt_text(client, _prompt_name(key), default_prompt)
    return resolved
