"""Push all prompts (system + tools) to Langfuse Production"""
import os
import sys
import subprocess

# --- 1. SET ENVIRONMENT VARIABLES FOR PRODUCTION ---
os.environ["LANGFUSE_SECRET_KEY"] = "sk-lf-b20df146-732b-47cb-9669-47983906eb93"
os.environ["LANGFUSE_PUBLIC_KEY"] = "pk-lf-611d32d6-e8c7-4e06-b5b5-c3486513a4a2"
os.environ["LANGFUSE_BASE_URL"] = "http://172.16.2.207:3009"

# We must import Langfuse AFTER setting os.environ, or initialize explicitly
from langfuse import Langfuse

def push_tools(lf):
    print("\n" + "="*60)
    print("🚀 PUSHING TOOL PROMPTS TO PRODUCTION")
    print("="*60)
    
    TOOL_PROMPTS_DIR = r"d:\cnf\chatbot_canifa\backend\agent\tool_prompts"
    
    # Matching the exact names used in backend/agent/prompt_utils.py
    TOOL_FILES = [
        ("brand_knowledge_tool.txt", "canifa-tool-brand-knowledge", ["canifa", "tool-prompt"]),
        ("check_is_stock.txt",       "canifa-tool-check-stock",     ["canifa", "tool-prompt"]),
        ("data_retrieval_tool.txt",  "canifa-tool-data-retrieval",  ["canifa", "tool-prompt"]),
        ("promotion_canifa_tool.txt","canifa-tool-promotion",       ["canifa", "tool-prompt"]),
        ("store_search_tool.txt",    "canifa-tool-store-search",    ["canifa", "tool-prompt"]),
    ]

    for filename, langfuse_name, tags in TOOL_FILES:
        path = os.path.join(TOOL_PROMPTS_DIR, filename)
        with open(path, "r", encoding="utf-8") as f:
            content = f.read()
        
        lf.create_prompt(
            name=langfuse_name,
            prompt=content,
            labels=["production"],
            tags=tags,
            type="text",
        )
        print(f"  ✅ {filename:30s} → {langfuse_name} ({len(content):,} chars)")
    
    lf.flush()
    print("✅ Tool prompts pushed successfully!\n")

def push_system_prompts():
    print("="*60)
    print("🚀 PUSHING SYSTEM PROMPTS TO PRODUCTION")
    print("="*60)
    
    # We can just call the existing push_modules_to_langfuse.py script 
    # since we already exported the env vars, it will pick up the prod credentials.
    script_dir = r"d:\cnf\chatbot_canifa\backend\agent\prompt_module"
    script_path = os.path.join(script_dir, "push_modules_to_langfuse.py")
    
    env = os.environ.copy()
    subprocess.run([sys.executable, script_path], cwd=script_dir, env=env, check=True)

if __name__ == "__main__":
    sys.stdout.reconfigure(encoding="utf-8")
    
    print("🌟 DEPLOYING TO C-STYLIST PRODUCTION 🌟")
    print(f"Target: {os.environ.get('LANGFUSE_BASE_URL')}")
    
    # 1. Push System Prompts
    push_system_prompts()
    
    # 2. Push Tool Prompts
    lf = Langfuse()
    push_tools(lf)
    
    print("🎉 ALL DEPLOYMENTS TO PRODUCTION FINISHED SUCCESSFULLY!")
