"""
Push ALL prompts (modules + tools) to PRODUCTION Langfuse.

Usage:  py push_prod.py
"""
import os
import sys

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

# ---- PRODUCTION Langfuse credentials ----
os.environ["LANGFUSE_SECRET_KEY"] = "sk-lf-bd0c7202-a7f4-4399-a36e-65ebe2e35104"
os.environ["LANGFUSE_PUBLIC_KEY"] = "pk-lf-2bb249b1-77e3-4309-8954-312b8fb2fff9"
os.environ["LANGFUSE_BASE_URL"]   = "http://172.16.2.207:3009"

from langfuse import Langfuse

BASE_DIR = os.path.dirname(os.path.abspath(__file__))
PROMPT_DIR = os.path.dirname(BASE_DIR)  # prompt_module/ (parent of push_production.py/)
TOOL_DIR = os.path.join(os.path.dirname(PROMPT_DIR), "tool_prompts")

# ---- Prompt modules ----
PROMPT_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"]),
    ("05b_tool_results.txt",    "canifa-05b-tool-results",   ["canifa", "system-core"]),
    ("05c_comparison.txt",      "canifa-05c-comparison",     ["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"]),
]

CORE_FILE = "01_core.txt"
CORE_PROMPT_NAME = "canifa-stylist-system-prompt"
SEASON_PROMPT_NAME = "canifa-08-season"

DEFAULT_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)
"""

# ---- Tool prompts ----
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(directory: str, filename: str) -> str:
    with open(os.path.join(directory, filename), "r", encoding="utf-8") as f:
        return f.read()


def main():
    print("🚀 PUSH ALL TO PRODUCTION LANGFUSE")
    print(f"   URL: {os.environ['LANGFUSE_BASE_URL']}")
    print()

    lf = Langfuse()

    # ── Step 1: Prompt modules ──
    print("=" * 60)
    print("STEP 1: Prompt Modules")
    print("=" * 60)

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

    # Season
    lf.create_prompt(name=SEASON_PROMPT_NAME, prompt=DEFAULT_SEASON_CONTENT,
                     labels=["production"], tags=["canifa", "system-addon"], type="text")
    print(f"  ✅ {'(season)':30s} → {SEASON_PROMPT_NAME}")

    # Core (with composable references)
    core_content = read_file(PROMPT_DIR, CORE_FILE)
    refs = "\n".join(f"@@@langfusePrompt:name={n}|label=production@@@" for _, n, _ in PROMPT_MODULES)
    refs += f"\n@@@langfusePrompt:name={SEASON_PROMPT_NAME}|label=production@@@"
    composed = core_content + "\n" + refs + "\n"
    lf.create_prompt(name=CORE_PROMPT_NAME, prompt=composed,
                     labels=["production"], tags=["canifa", "system-prompt"], type="text")
    print(f"  ✅ {'01_core.txt (composed)':30s} → {CORE_PROMPT_NAME}")

    # ── Step 2: Tool prompts ──
    print("\n" + "=" * 60)
    print("STEP 2: Tool Prompts")
    print("=" * 60)

    for filename, name, tags in TOOL_PROMPTS:
        filepath = os.path.join(TOOL_DIR, filename)
        if not os.path.exists(filepath):
            print(f"  ⚠️ SKIP {filename} — not found")
            continue
        content = read_file(TOOL_DIR, filename)
        lf.create_prompt(name=name, prompt=content, labels=["production"], tags=tags, type="text")
        print(f"  ✅ {filename:35s} → {name} ({len(content):,} chars)")

    # ── Step 3: Verify ──
    print("\n" + "=" * 60)
    print("STEP 3: Verification")
    print("=" * 60)

    prompt = lf.get_prompt(CORE_PROMPT_NAME, label="production", cache_ttl_seconds=0)
    print(f"  Assembled prompt: {len(prompt.prompt):,} chars")

    checks = [
        ("01 Core",        "C-stylist"),
        ("02 Rules",       "QUY TẮC TRUNG THỰC"),
        ("03 Context",     "CONTEXT AWARENESS"),
        ("04a Sales",      "PHONG CÁCH TƯ VẤN"),
        ("05 Tool Route",  "KHI NÀO GỌI TOOL"),
        ("05b Results",    "XỬ LÝ KẾT QUẢ TOOL"),
        ("05c Compare",    "SO SÁNH"),
        ("06 Insight",     "USER INSIGHT 2.0"),
        ("07 Output",      "FORMAT ĐẦU RA"),
        ("08 Season",      "HƯỚNG DẪN TƯ VẤN THEO MÙA"),
    ]

    all_ok = True
    for label, keyword in checks:
        found = keyword in prompt.prompt
        print(f"  {'✅' if found else '❌'} {label}: '{keyword}'")
        if not found:
            all_ok = False

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

    lf.flush()
    print(f"\n{'🎉 ALL DONE!' if all_ok else '⚠️ Done with warnings'}")


if __name__ == "__main__":
    main()
