"""
Push ALL prompts (system + tools) to Langfuse.
This is the master script — run this when setting up a new Langfuse instance.

Usage: python agent/prompt_module/push_all_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

PROMPT_DIR = os.path.dirname(os.path.abspath(__file__))
TOOL_PROMPT_DIR = os.path.join(PROMPT_DIR, "..", "tool_prompts")


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


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

    lf = Langfuse()

    # ============================================================
    # PART 1: System Prompt Sub-Modules (02-07 + season)
    # ============================================================
    print("\n" + "=" * 60)
    print("PART 1: System Prompt Sub-Modules")
    print("=" * 60)

    SUB_MODULES = [
        ("02_rules.txt",            "canifa-02-rules",           ["canifa", "system-core"]),
        ("03_context.txt",          "canifa-03-context",         ["canifa", "system-core"]),
        ("04a_sales_core.txt",      "canifa-04a-sales-core",     ["canifa", "system-sales"]),
        ("04b_sales_thaomai.txt",   "canifa-04b-sales-thaomai",  ["canifa", "system-sales"]),
        ("04c_sales_upsell.txt",    "canifa-04c-sales-upsell",   ["canifa", "system-sales"]),
        ("04d_sales_urgency.txt",   "canifa-04d-sales-urgency",  ["canifa", "system-sales"]),
        ("05_tool_routing.txt",     "canifa-05-tool-routing",    ["canifa", "system-core"]),
        ("06_user_insight.txt",     "canifa-06-user-insight",    ["canifa", "system-core"]),
        ("07_output_format.txt",    "canifa-07-output-format",   ["canifa", "system-core"]),
    ]

    for filename, langfuse_name, tags in SUB_MODULES:
        content = read_file(os.path.join(PROMPT_DIR, filename))
        lf.create_prompt(name=langfuse_name, prompt=content, labels=["production"], tags=tags, type="text")
        print(f"  ✅ {filename:30s} → {langfuse_name} ({len(content):,} chars)")

    # Season prompt
    SEASON_CONTENT = """## HƯỚNG DẪN TƯ VẤN THEO MÙA / EVENT

**Thời điểm hiện tại:** Tháng 3/2026 — Mùa Xuân, chuyển giao Đông → Hè

**Ưu tiên sản phẩm mùa này:**
- Áo khoác nhẹ, cardigan (trời se lạnh buổi sáng/tối)
- Áo phông, áo thun (ban ngày ấm)
- Sơ mi dài tay (đi làm)
- Quần jeans, quần kaki (đa năng)

**Khi khách hỏi chung chung ("có gì hot?", "gợi ý đi"):**
→ Ưu tiên giới thiệu sản phẩm phù hợp thời tiết hiện tại
→ Nhắc sale/khuyến mãi nếu có

**Event đang diễn ra:**
- (Marketing cập nhật event tại đây)
"""
    lf.create_prompt(name="canifa-08-season", prompt=SEASON_CONTENT, labels=["production"], tags=["canifa", "system-addon"], type="text")
    print(f"  ✅ {'(season template)':30s} → canifa-08-season ({len(SEASON_CONTENT):,} chars)")

    # ============================================================
    # PART 2: Core System Prompt (01_core + references)
    # ============================================================
    print("\n" + "=" * 60)
    print("PART 2: Core System Prompt (composable)")
    print("=" * 60)

    core_content = read_file(os.path.join(PROMPT_DIR, "01_core.txt"))
    references = "\n".join(
        f"@@@langfusePrompt:name={name}|label=production@@@"
        for _, name, _ in SUB_MODULES
    )
    references += "\n@@@langfusePrompt:name=canifa-08-season|label=production@@@"
    composed = core_content + "\n" + references + "\n"

    lf.create_prompt(name="canifa-stylist-system-prompt", prompt=composed, labels=["production"], tags=["canifa", "system-prompt"], type="text")
    print(f"  ✅ canifa-stylist-system-prompt ({len(composed):,} chars, {len(SUB_MODULES) + 1} refs)")

    # ============================================================
    # PART 3: Tool Prompts (with correct Langfuse names!)
    # ============================================================
    print("\n" + "=" * 60)
    print("PART 3: Tool Prompts")
    print("=" * 60)

    TOOL_PROMPTS = {
        "brand_knowledge_tool.txt": "canifa-tool-brand-knowledge",
        "check_is_stock.txt":       "canifa-tool-check-stock",
        "data_retrieval_tool.txt":  "canifa-tool-data-retrieval",
        "promotion_canifa_tool.txt": "canifa-tool-promotion",
        "store_search_tool.txt":    "canifa-tool-store-search",
    }

    for filename, langfuse_name in TOOL_PROMPTS.items():
        path = os.path.join(TOOL_PROMPT_DIR, filename)
        content = read_file(path)
        lf.create_prompt(name=langfuse_name, prompt=content, labels=["production"], tags=["canifa", "tool-prompt"], type="text")
        print(f"  ✅ {filename:35s} → {langfuse_name} ({len(content):,} chars)")

    # ============================================================
    # VERIFY
    # ============================================================
    print("\n" + "=" * 60)
    print("VERIFICATION")
    print("=" * 60)

    prompt = lf.get_prompt("canifa-stylist-system-prompt", label="production", cache_ttl_seconds=0)
    assembled = prompt.prompt
    print(f"  System prompt assembled: {len(assembled):,} chars")

    for tool_name, langfuse_name in TOOL_PROMPTS.items():
        try:
            p = lf.get_prompt(langfuse_name, label="production", cache_ttl_seconds=0)
            print(f"  ✅ {langfuse_name}: {len(p.prompt):,} chars")
        except Exception as e:
            print(f"  ❌ {langfuse_name}: {e}")

    lf.flush()
    print("\n🎉 ALL PROMPTS PUSHED SUCCESSFULLY!")


if __name__ == "__main__":
    main()
