"""
Push prompt modules to Langfuse as composable prompts.
Creates individual sub-module prompts, then updates the core system prompt
to reference them via @@@langfusePrompt:...@@@ tags.

Usage:  python push_modules_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__))

# ---- Module definitions: local file → Langfuse name (NUMBERED) + tags ----
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"]),
]

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

# Default season content
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)
"""


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


def push_sub_modules(lf: Langfuse):
    """Push each sub-module file as a separate Langfuse text prompt."""
    print("\n" + "=" * 60)
    print("STEP 1: Pushing sub-module prompts (NUMBERED)")
    print("=" * 60)

    for filename, langfuse_name, tags in SUB_MODULES:
        content = read_file(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 with default content
    lf.create_prompt(
        name=SEASON_PROMPT_NAME,
        prompt=DEFAULT_SEASON_CONTENT,
        labels=["production"],
        tags=["canifa", "system-addon"],
        type="text",
    )
    print(f"  ✅ {'(season template)':30s} → {SEASON_PROMPT_NAME} ({len(DEFAULT_SEASON_CONTENT):,} chars)")


def push_core_with_references(lf: Langfuse):
    """Push the core prompt with @@@langfusePrompt:...@@@ references."""
    print("\n" + "=" * 60)
    print("STEP 2: Pushing core prompt with composable references")
    print("=" * 60)

    core_content = read_file(CORE_FILE)

    # Build the composed prompt: core inline + references to sub-modules
    references = "\n".join(
        f"@@@langfusePrompt:name={name}|label=production@@@"
        for _, name, _ in SUB_MODULES
    )

    # Add season reference at the end
    references += f"\n@@@langfusePrompt:name={SEASON_PROMPT_NAME}|label=production@@@"

    composed = core_content + "\n" + references + "\n"

    lf.create_prompt(
        name=CORE_PROMPT_NAME,
        prompt=composed,
        labels=["production"],
        tags=["canifa", "system-prompt"],
        type="text",
    )
    print(f"  ✅ Core prompt updated: {CORE_PROMPT_NAME}")
    print(f"     Inline: {CORE_FILE} ({len(core_content):,} chars)")
    print(f"     References: {len(SUB_MODULES) + 1} sub-modules")


def verify(lf: Langfuse):
    """Verify the assembled prompt contains all sections."""
    print("\n" + "=" * 60)
    print("STEP 3: Verification")
    print("=" * 60)

    # Fetch the composed prompt — Langfuse auto-resolves references
    prompt = lf.get_prompt(CORE_PROMPT_NAME, label="production", cache_ttl_seconds=0)
    assembled = prompt.prompt

    print(f"  Assembled prompt length: {len(assembled):,} chars")

    # Check key section headings exist in assembled output
    checks = [
        ("01 Identity (core)",   "Canifa-AI Stylist"),
        ("02 Rules",             "QUY TẮC TRUNG THỰC"),
        ("03 Context",           "CONTEXT AWARENESS"),
        ("04a Sales Core",       "PHONG CÁCH TƯ VẤN"),
        ("04b Thảo Mai",         "THẢO MAI SALES"),
        ("04c Upsell",           "UPSELL & CROSS-SELL"),
        ("04d Urgency",          "URGENCY TACTICS"),
        ("05 Tool Routing",      "KHI NÀO GỌI TOOL"),
        ("06 User Insight",      "USER INSIGHT 2.0"),
        ("07 Output Format",     "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 assembled
        status = "✅" if found else "❌ MISSING"
        print(f"  {status} {label}: '{keyword}'")
        if not found:
            all_ok = False

    if all_ok:
        print("\n  🎉 ALL CHECKS PASSED!")
    else:
        print("\n  ⚠️ SOME CHECKS FAILED — review above")

    return all_ok


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

    lf = Langfuse()

    push_sub_modules(lf)
    push_core_with_references(lf)
    ok = verify(lf)

    lf.flush()  # ensure all API calls complete
    print("\n✅ Done!" if ok else "\n⚠️ Done with warnings")


if __name__ == "__main__":
    main()
