"""
Integration test for rag-basic template.
Tests the full workflow: create assistant, upload docs, chat.
"""

import os
import shutil
import subprocess
import sys
import tempfile
from pathlib import Path


def run_command(cmd, cwd=None, input_text=None):
    """Run command and return success status and output."""
    result = subprocess.run(
        cmd, cwd=cwd, capture_output=True, text=True, input=input_text
    )
    return result.returncode == 0, result.stdout, result.stderr


def test_rag_basic_template():
    """Test the complete rag-basic template workflow."""
    test_name = "test_template_rag"
    test_dir = None

    try:
        test_dir = tempfile.mkdtemp(prefix="pygeai_template_test_")
        print(f"Testing in: {test_dir}")

        print("\n1. Generating project from rag-basic template...")
        success, stdout, stderr = run_command(
            [
                "geai",
                "generate",
                "create",
                "--template",
                "rag-basic",
                "--output",
                test_dir,
                "--no-interactive",
                "--name",
                test_name,
                "--description",
                "Test RAG assistant for template validation",
                "--model",
                "gpt-3.5-turbo",
            ]
        )

        if not success:
            print(f"[FAIL] Failed to generate project:\n{stderr}")
            return False
        print("[PASS] Project generated successfully")

        print("\n2. Creating test document...")
        docs_dir = Path(test_dir) / "documents"
        test_doc = docs_dir / "test_info.txt"
        test_doc.write_text("""
PyGEAI Template Testing

This document is used for testing the rag-basic template.
It contains information about template validation and testing procedures.

The template generator creates:
- Assistant creation scripts
- Document upload utilities  
- Interactive chat interfaces

All scripts use the PyGEAI SDK and follow best practices.
""")
        print(f"[PASS] Created test document: {test_doc}")

        print(f"\n3. Cleaning up any existing assistant '{test_name}'...")
        run_command(["geai", "rag", "delete-assistant", "--name", test_name])

        print("\n4. Creating RAG assistant...")
        success, stdout, stderr = run_command(
            ["python", f"create_{test_name}.py"], cwd=test_dir
        )

        if not success or "Error" in stderr:
            print(f"[FAIL] Failed to create assistant:\n{stdout}\n{stderr}")
            return False
        print("[PASS] Assistant created successfully")

        print("\n5. Uploading documents...")
        success, stdout, stderr = run_command(
            ["python", "upload_documents.py"], cwd=test_dir
        )

        if not success:
            print(f"[FAIL] Failed to upload documents:\n{stdout}\n{stderr}")
            return False

        if "✓" not in stdout:
            print(f"[FAIL] No documents uploaded successfully:\n{stdout}")
            return False
        print("[PASS] Documents uploaded successfully")

        print("\n6. Testing chat functionality...")
        import time

        print("Waiting for document indexing to complete...")
        time.sleep(3)

        success, stdout, stderr = run_command(
            ["geai", "chat", "search", "--name", test_name],
            input_text="What is this document about?\nexit\n",
        )

        if not success:
            print(f"[FAIL] Chat failed:\n{stdout}\n{stderr}")
            return False

        if "template" not in stdout.lower() or "testing" not in stdout.lower():
            print(
                "[WARN] Chat response may not contain document content (indexing delay)"
            )
            print(f"Response preview: {stdout[:500]}")
        else:
            print("[PASS] Chat functionality works correctly")

        print("\n" + "=" * 60)
        print("[PASS] ALL TESTS PASSED - rag-basic template is working correctly!")
        print("=" * 60)
        return True

    except Exception as e:
        print(f"\n[FAIL] Test failed with exception: {e}")
        import traceback

        traceback.print_exc()
        return False

    finally:
        if test_dir and os.path.exists(test_dir):
            print(f"\nCleaning up test directory: {test_dir}")
            shutil.rmtree(test_dir)

        print(f"Deleting test assistant: {test_name}")
        run_command(["geai", "rag", "delete-assistant", "--name", test_name])


if __name__ == "__main__":
    success = test_rag_basic_template()
    sys.exit(0 if success else 1)
