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_web_ui_gradio_template():
    """
    Test web-ui-gradio template by:
    1. Generating the template files
    2. Verifying all files exist
    3. Checking file contents
    """
    test_dir = tempfile.mkdtemp(prefix="pygeai_gradio_test_")

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

    try:
        print("[STEP 1] Generating web-ui-gradio template...")
        engine = TemplateEngine()

        params = {
            "name": "test_gradio_ui",
            "description": "Test Gradio Web UI",
        }

        generated_files = engine.generate("web-ui-gradio", Path(test_dir), params)

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

        app_py = Path(test_dir) / "app.py"
        requirements = Path(test_dir) / "requirements.txt"
        readme = Path(test_dir) / "README.md"

        assert app_py.exists(), "app.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...")

        app_content = app_py.read_text()
        assert "import gradio as gr" in app_content, "Gradio not imported"
        assert "test_gradio_ui" in app_content, "Project name not in app.py"
        assert "chat_with_model" in app_content, "Chat function not defined"
        assert "demo.launch" in app_content, "Launch call not found"
        assert "ChatClient" in app_content, "ChatClient not imported"
        print("[PASS] app.py contains expected content")

        req_content = requirements.read_text()
        assert "gradio" in req_content, "gradio 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_gradio_ui" in readme_content, "Project name not in README"
        assert "Gradio" in readme_content, "Gradio not mentioned"
        assert "http://localhost:7860" in readme_content, "Port not documented"
        print("[PASS] README contains expected documentation")

        print(
            "\n[PASS] ALL TESTS PASSED - web-ui-gradio 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_web_ui_gradio_template()
