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
from pygeai.lab.managers import AILabManager
from pygeai.lab.models import Agent, AgentData, Prompt, LlmConfig, Model, Sampling


def test_lab_process_basic_template():
    """
    Test lab-process-basic template by:
    1. Creating prerequisite agent
    2. Generating template files
    3. Creating all process components
    4. Verifying process creation
    """
    test_dir = tempfile.mkdtemp(prefix="pygeai_process_test_")
    agent_name = f"test_process_agent_{os.urandom(4).hex()}"
    task_name = f"test_task_{os.urandom(4).hex()}"
    process_name = f"test_process_{os.urandom(4).hex()}"

    agent_id = None
    artifact_type_id = None
    kb_id = None
    task_id = None
    process_id = None

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

    try:
        manager = AILabManager()

        print("[STEP 1] Creating prerequisite agent...")
        agent = Agent(
            name=agent_name,
            description="Test agent for process",
            access_scope="private",
            agent_data=AgentData(
                prompt=Prompt(
                    instructions="You are a test agent for process workflows.",
                    inputs=["input"],
                    outputs=[],
                ),
                llm_config=LlmConfig(
                    max_tokens=100, timeout=60, sampling=Sampling(temperature=0.5)
                ),
                models=[Model(name="gpt-4")],
            ),
        )

        result = manager.create_agent(agent=agent, automatic_publish=True)
        agent_id = result.id
        print(f"[PASS] Agent created: {agent_id}")

        print("[STEP 2] Generating lab-process-basic template...")
        engine = TemplateEngine()

        params = {
            "name": process_name,
            "description": "Test agentic process",
            "agent_name": agent_name,
            "task_name": task_name,
        }

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

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

        print("[STEP 3] Creating artifact type...")
        artifact_type = manager.create_artifact_type(
            name=f"{process_name}_artifact",
            description=f"Artifact type for {process_name} process",
            tag=process_name,
        )
        artifact_type_id = artifact_type.id
        print(f"[PASS] Artifact type created: {artifact_type_id}")

        print("[STEP 4] Creating knowledge base...")
        from pygeai.lab.models import KnowledgeBase

        kb = KnowledgeBase(
            name=f"{process_name}_kb",
            artifact_type_name=[f"{process_name}_artifact"],
            metadata=[],
        )
        kb_result = manager.create_knowledge_base(knowledge_base=kb)
        kb_id = kb_result.id
        print(f"[PASS] Knowledge base created: {kb_id}")

        print("[STEP 5] Creating task...")
        from pygeai.lab.models import Task

        task = Task(
            name=task_name,
            description="Test agentic process",
            title_template=f"{process_name} Task",
        )
        task_result = manager.create_task(task=task, automatic_publish=True)
        task_id = task_result.id
        print(f"[PASS] Task created: {task_id}")

        print("[STEP 6] Creating process...")
        from pygeai.lab.models import (
            AgenticProcess,
            AgenticActivity,
            ArtifactSignal,
            UserSignal,
            Event,
            SequenceFlow,
        )

        process = AgenticProcess(
            key=process_name,
            name=process_name,
            description="Test agentic process",
            kb=KnowledgeBase(
                name=f"{process_name}_kb",
                artifact_type_name=[f"{process_name}_artifact"],
            ),
            agentic_activities=[
                AgenticActivity(
                    key="main_activity",
                    name="Main Task",
                    task_name=task_name,
                    agent_name=agent_name,
                    agent_revision_id=0,
                )
            ],
            artifact_signals=[
                ArtifactSignal(
                    key="artifact_uploaded",
                    name="artifact.upload",
                    handling_type="C",
                    artifact_type_name=[f"{process_name}_artifact"],
                )
            ],
            user_signals=[
                UserSignal(key="process_completed", name="process-completed")
            ],
            start_event=Event(key="artifact_uploaded", name="artifact.upload"),
            end_event=Event(key="end", name="Done"),
            sequence_flows=[
                SequenceFlow(
                    key="flow1",
                    source_key="artifact_uploaded",
                    target_key="main_activity",
                ),
                SequenceFlow(
                    key="flow2",
                    source_key="main_activity",
                    target_key="process_completed",
                ),
                SequenceFlow(
                    key="flow3", source_key="process_completed", target_key="end"
                ),
            ],
        )

        process_result = manager.create_process(process=process, automatic_publish=True)
        process_id = process_result.id
        print(f"[PASS] Process created: {process_id}")

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

        if task_id:
            try:
                manager.delete_task(task_id=task_id)
                print(f"Deleted task: {task_id}")
            except Exception as e:
                print(f"Warning: Could not delete task: {e}")

        if kb_id:
            try:
                manager.delete_knowledge_base(kb_id=kb_id)
                print(f"Deleted knowledge base: {kb_id}")
            except Exception as e:
                print(f"Warning: Could not delete KB: {e}")

        if artifact_type_id:
            try:
                manager.delete_artifact_type(id_or_name=artifact_type_id)
                print(f"Deleted artifact type: {artifact_type_id}")
            except Exception as e:
                print(f"Warning: Could not delete artifact type: {e}")

        if agent_id:
            try:
                manager.delete_agent(agent_id=agent_id)
                print(f"Deleted 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_process_basic_template()
