"""
Push tool prompts to Langfuse.
Updates individual tool description prompts.

Usage:  python push_tools_to_langfuse.py
"""
import os
import sys

sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", ".."))
sys.stdout.reconfigure(encoding="utf-8")

from dotenv import load_dotenv
load_dotenv(os.path.join(os.path.dirname(__file__), "..", "..", ".env"))

from langfuse import Langfuse

TOOL_DIR = os.path.dirname(os.path.abspath(__file__))

# ---- Tool prompt definitions: local file → Langfuse name ----
TOOL_PROMPTS = [
    ("data_retrieval_tool.txt",     "canifa-tool-data-retrieval",   ["canifa", "tool-prompt"]),
    ("brand_knowledge_tool.txt",    "canifa-tool-brand-knowledge",  ["canifa", "tool-prompt"]),
    ("check_is_stock.txt",          "canifa-tool-check-is-stock",   ["canifa", "tool-prompt"]),
    ("store_search_tool.txt",       "canifa-tool-store-search",     ["canifa", "tool-prompt"]),
    ("promotion_canifa_tool.txt",   "canifa-tool-promotion",        ["canifa", "tool-prompt"]),
]


def read_file(filename: str) -> str:
    path = os.path.join(TOOL_DIR, filename)
    with open(path, "r", encoding="utf-8") as f:
        return f.read()


def push_tools(lf: Langfuse):
    """Push each tool prompt file as a Langfuse text prompt."""
    print("\n" + "=" * 60)
    print("Pushing tool prompts")
    print("=" * 60)

    for filename, langfuse_name, tags in TOOL_PROMPTS:
        filepath = os.path.join(TOOL_DIR, filename)
        if not os.path.exists(filepath):
            print(f"  ⚠️ SKIP {filename} — file not found")
            continue

        content = read_file(filename)
        lf.create_prompt(
            name=langfuse_name,
            prompt=content,
            labels=["production"],
            tags=tags,
            type="text",
        )
        print(f"  ✅ {filename:35s} → {langfuse_name} ({len(content):,} chars)")


def verify(lf: Langfuse):
    """Verify tool prompts are accessible."""
    print("\n" + "=" * 60)
    print("Verification")
    print("=" * 60)

    all_ok = True
    for filename, langfuse_name, _ in TOOL_PROMPTS:
        filepath = os.path.join(TOOL_DIR, filename)
        if not os.path.exists(filepath):
            continue
        try:
            prompt = lf.get_prompt(langfuse_name, label="production", cache_ttl_seconds=0)
            print(f"  ✅ {langfuse_name} — {len(prompt.prompt):,} chars")
        except Exception as e:
            print(f"  ❌ {langfuse_name} — {e}")
            all_ok = False

    if all_ok:
        print("\n  🎉 ALL TOOL PROMPTS PUSHED!")
    else:
        print("\n  ⚠️ SOME CHECKS FAILED")

    return all_ok


def main():
    print("🚀 Push Tool Prompts to Langfuse")
    print(f"   Langfuse URL: {os.getenv('LANGFUSE_BASE_URL')}")

    lf = Langfuse()

    push_tools(lf)
    ok = verify(lf)

    lf.flush()
    print("\n✅ Done!" if ok else "\n⚠️ Done with warnings")


if __name__ == "__main__":
    main()
