#!/usr/bin/env python3
"""Read file_refs.txt (header) + answer_body.txt (agent answer) → write combined to final_answer.txt + print.

Usage: python3 format_answer.py

Reads from session directory:
  ./file_refs.txt   — written by search.py (F1=uuid(name) format)
  ./answer_body.txt — written by agent (answer text with <CITATION> tags)

Writes: ./final_answer.txt (header + body combined, ready for cat)
Also prints to stdout for immediate visibility.
"""
import os
import sys

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from _session import get_session_dir

BODY_FILE = "./answer_body.txt"


def main():
    REFS_FILE = os.path.join(get_session_dir(), "file_refs.txt")
    # Read header from file_refs.txt
    header_lines = []
    if os.path.exists(REFS_FILE):
        with open(REFS_FILE, "r", encoding="utf-8") as f:
            for line in f:
                line = line.strip()
                if not line:
                    continue
                # Convert F1=uuid(name) → F1 = uuid (name)
                if "=" in line and line[0] == "F":
                    parts = line.split("=", 1)
                    ref = parts[0].strip()
                    rest = parts[1].strip()
                    header_lines.append(f"{ref} = {rest}")
                else:
                    header_lines.append(line)

    else:
        print("WARNING: file_refs.txt not found, outputting answer without header", file=sys.stderr)

    # Read answer body
    if not os.path.exists(BODY_FILE):
        print(f"ERROR: {BODY_FILE} not found. Write your answer to {BODY_FILE} first.", file=sys.stderr)
        sys.exit(1)

    with open(BODY_FILE, "r", encoding="utf-8") as f:
        body = f.read().strip()

    # Build combined output
    parts = []
    if header_lines:
        parts.append("\n".join(header_lines))
        parts.append("")
    parts.append(body)
    combined = "\n".join(parts)

    # Write to file (agent will cat this)
    with open("./final_answer.txt", "w", encoding="utf-8") as f:
        f.write(combined)

    # Also print for immediate visibility
    print(f"Written to ./final_answer.txt ({len(combined)} chars)")
    print()
    print(combined)


if __name__ == "__main__":
    main()
