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

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

from pygeai.templates.engine import TemplateEngine
from pygeai.lab.managers import AILabManager
from pygeai.lab.runners import Runner


def test_lab_agent_basic_template():
    test_dir = tempfile.mkdtemp(prefix="pygeai_lab_template_test_")
    agent_name = f"test_lab_agent_{os.urandom(4).hex()}"
    agent_id = None

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

    try:
        engine = TemplateEngine()

        params = {
            "name": agent_name,
            "description": "Test agent for template validation",
            "instructions": "You are a test agent. Echo back what the user says with 'TEST:' prefix.",
            "model": "gpt-4",
            "temperature": "0.5",
            "max_tokens": "100",
        }

        generated_files = engine.generate("lab-agent-basic", Path(test_dir), params)

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

        create_script = Path(test_dir) / f"create_{agent_name}.py"
        run_script = Path(test_dir) / f"run_{agent_name}.py"
        readme = Path(test_dir) / "README.md"

        assert create_script.exists(), "create script not found"
        assert run_script.exists(), "run script not found"
        assert readme.exists(), "README not found"

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

        result = subprocess.run(
            [sys.executable, str(create_script)],
            cwd=test_dir,
            capture_output=True,
            text=True,
            timeout=30,
        )

        if result.returncode != 0:
            print("[FAIL] Agent creation failed:")
            print(f"STDOUT: {result.stdout}")
            print(f"STDERR: {result.stderr}")
            sys.exit(1)

        print("[PASS] Agent created successfully")
        print(f"Output: {result.stdout}")

        for line in result.stdout.split("\n"):
            if "ID:" in line:
                agent_id = line.split("ID:")[-1].strip()
                break

        if not agent_id:
            print("[FAIL] Could not extract agent ID from output")
            sys.exit(1)

        manager = AILabManager()
        agent = manager.get_agent(agent_id=agent_id)

        if not agent:
            print(f"[FAIL] Could not retrieve agent '{agent_id}'")
            sys.exit(1)

        print("[PASS] Agent retrieved successfully")

        async def test_agent_run():
            response = await Runner.run(agent=agent, user_input="Hello, test!")
            return response

        response = asyncio.run(test_agent_run())

        if response:
            print("[PASS] Agent executed successfully")
            print(f"Response: {response}")
        else:
            print("[WARN] Agent returned empty response")

        print(
            "\n[PASS] ALL TESTS PASSED - lab-agent-basic 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 agent_id:
            try:
                manager = AILabManager()
                manager.delete_agent(agent_id=agent_id)
                print(f"Deleted test agent: {agent_id}")
            except Exception as e:
                print(f"Warning: Could not delete agent: {e}")

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


if __name__ == "__main__":
    test_lab_agent_basic_template()
