"""
Split system_prompt.txt into 10 module files.
Cut at exact heading boundaries. Verify reassembly = original.
"""
import os
import re
import sys

sys.stdout.reconfigure(encoding='utf-8')

PROMPT_DIR = os.path.dirname(os.path.abspath(__file__))
SOURCE = os.path.join(os.path.dirname(PROMPT_DIR), "system_prompt.txt")

# Read file
with open(SOURCE, "r", encoding="utf-8") as f:
    full_text = f.read()

lines = full_text.split("\n")
print(f"Total lines: {len(lines)}")
print(f"Total chars: {len(full_text)}")

# --- Find exact line indices for each section boundary ---
# We search for the FIRST occurrence of each heading pattern

boundaries = {}
heading_patterns = [
    ("rules_start",     r"^## 1\. QUY T"),
    ("context_start",   r"^## 3\. CONTEXT"),
    ("sales_start",     r"^## 4\. PHONG C"),
    ("thaomai_start",   r"^### 4\.5\. .* TH"),
    ("upsell_start",    r"^### 4\.6\. .* UPSELL"),
    ("urgency_start",   r"^### 4\.7\. .* KHU"),
    ("tool_start",      r"^## 5\. KHI N"),
    ("insight_start",   r"^## 8\. USER INSIGHT"),
    ("output_start",    r"^## 9\. FORMAT"),
]

for key, pattern in heading_patterns:
    for i, line in enumerate(lines):
        if re.search(pattern, line):
            boundaries[key] = i
            print(f"  {key} = line {i+1} (0-indexed: {i}): {line[:60].strip()}")
            break
    else:
        print(f"  WARNING: {key} NOT FOUND!")

# Now we also need to find where to cut BEFORE each heading.
# Some headings have a "---" separator above them that belongs to the PREVIOUS section.
# We want to cut so the "---" before a heading goes with the previous file.

# Let's look just before each heading to see if there's a "---" separator
def find_cut_point(line_idx):
    """Find the actual cut point: include preceding blank lines and --- in prev section."""
    # The heading itself starts the new section
    # But we want to include any preceding "---" and blank lines in the PREVIOUS section
    # So the new section starts AT the heading line
    return line_idx

# Define file mappings: (filename, start_line_idx, end_line_idx_exclusive)
# We'll compute them from boundaries

b = boundaries

# Helper: check if the line before heading is "---" and blank lines
# If so, include them in prev section
def prev_separator_end(heading_idx):
    """Find where the CURRENT section truly starts (at or after heading_idx).
    We look backward: if there's a --- and blank lines before the heading,
    those belong to the PREVIOUS section. The heading line itself starts the new section."""
    # But actually for the "---" that comes BEFORE section X, it's usually the 
    # separator at the END of section X-1. So we want:
    # - Previous section includes up to (and including) the "---" before the heading
    # - New section starts at the heading line
    
    # Look backward from heading
    idx = heading_idx
    # Check if preceding lines are blank or "---"
    while idx > 0 and lines[idx-1].strip() in ("", "---"):
        idx -= 1
    # The "---" and blanks before heading belong to previous section
    # So previous section ends at heading_idx - 1 (inclusive)
    # New section starts at heading_idx
    return heading_idx


modules = [
    ("01_core.txt",             0,                             b["rules_start"]),
    ("02_rules.txt",            b["rules_start"],              b["context_start"]),
    ("03_context.txt",          b["context_start"],            b["sales_start"]),
    ("04a_sales_core.txt",      b["sales_start"],              b["thaomai_start"]),
    ("04b_sales_thaomai.txt",   b["thaomai_start"],            b["upsell_start"]),
    ("04c_sales_upsell.txt",    b["upsell_start"],             b["urgency_start"]),
    ("04d_sales_urgency.txt",   b["urgency_start"],            b["tool_start"]),
    ("05_tool_routing.txt",     b["tool_start"],               b["insight_start"]),
    ("06_user_insight.txt",     b["insight_start"],            b["output_start"]),
    ("07_output_format.txt",    b["output_start"],             len(lines)),
]

# Write each module
print("\n--- Writing module files ---")
for filename, start, end in modules:
    content = "\n".join(lines[start:end])
    filepath = os.path.join(PROMPT_DIR, filename)
    with open(filepath, "w", encoding="utf-8") as f:
        f.write(content)
    line_count = end - start
    print(f"  {filename}: lines {start+1}-{end} ({line_count} lines, {len(content)} chars)")

# Verify: reassemble and compare
print("\n--- Verification ---")
reassembled_parts = []
for filename, start, end in modules:
    filepath = os.path.join(PROMPT_DIR, filename)
    with open(filepath, "r", encoding="utf-8") as f:
        reassembled_parts.append(f.read())

reassembled = "\n".join(reassembled_parts)

if reassembled == full_text:
    print("✅ PASS: Reassembled content MATCHES original exactly!")
    print(f"   Original:    {len(full_text)} chars")
    print(f"   Reassembled: {len(reassembled)} chars")
else:
    print("❌ FAIL: Reassembled content does NOT match original!")
    print(f"   Original:    {len(full_text)} chars")
    print(f"   Reassembled: {len(reassembled)} chars")
    # Find first difference
    for i, (a, b_char) in enumerate(zip(full_text, reassembled)):
        if a != b_char:
            print(f"   First diff at char {i}: original='{repr(a)}' reassembled='{repr(b_char)}'")
            print(f"   Context original:    ...{repr(full_text[max(0,i-20):i+20])}...")
            print(f"   Context reassembled: ...{repr(reassembled[max(0,i-20):i+20])}...")
            break

print("\nDone!")
