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

sys.path.insert(0, str(Path(__file__).parent.parent.parent.parent))

from pygeai.templates.engine import TemplateEngine


def test_api_server_template():
    """
    Test api-server template by:
    1. Generating the template files
    2. Verifying all files exist
    3. Checking file contents
    """
    test_dir = tempfile.mkdtemp(prefix="pygeai_api_test_")

    print(f"Testing in: {test_dir}")

    try:
        print("[STEP 1] Generating api-server template...")
        engine = TemplateEngine()

        params = {
            "name": "test_api",
            "description": "Test API Server",
        }

        generated_files = engine.generate("api-server", Path(test_dir), params)

        assert len(generated_files) == 3, (
            f"Expected 3 files, got {len(generated_files)}"
        )
        print("[PASS] Template generated successfully")

        server_py = Path(test_dir) / "server.py"
        requirements = Path(test_dir) / "requirements.txt"
        readme = Path(test_dir) / "README.md"

        assert server_py.exists(), "server.py not found"
        assert requirements.exists(), "requirements.txt not found"
        assert readme.exists(), "README.md not found"

        print("[PASS] All expected files exist")

        print("[STEP 2] Verifying file contents...")

        server_content = server_py.read_text()
        assert "FastAPI" in server_content, "FastAPI not imported"
        assert "test_api" in server_content, "Project name not in server.py"
        assert "/chat" in server_content, "Chat endpoint not defined"
        assert "/chat/stream" in server_content, "Streaming endpoint not defined"
        print("[PASS] server.py contains expected content")

        req_content = requirements.read_text()
        assert "fastapi" in req_content, "fastapi not in requirements"
        assert "uvicorn" in req_content, "uvicorn not in requirements"
        assert "pygeai" in req_content, "pygeai not in requirements"
        print("[PASS] requirements.txt contains expected dependencies")

        readme_content = readme.read_text()
        assert "test_api" in readme_content, "Project name not in README"
        assert "POST /chat" in readme_content, "API documentation missing"
        print("[PASS] README contains expected documentation")

        print("\n[PASS] ALL TESTS PASSED - api-server template is working correctly!")

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

        traceback.print_exc()
        sys.exit(1)

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


if __name__ == "__main__":
    test_api_server_template()
