# testor.py
import os
import uuid
from core import SuperU

# Load API key
SUPERU_API_KEY = os.getenv("SUPERU_API_KEY")

if not SUPERU_API_KEY:
    raise Exception("SUPERU_API_KEY not set in environment")

print("Using API Key:", SUPERU_API_KEY[:6] + "******")

# Initialize client
superu = SuperU(SUPERU_API_KEY)

print("✅ SuperU client initialized")
print("User ID:", superu.user_id)

# ---- Basic smoke tests ----

def _extract_list(response: dict, candidate_keys: list[str]) -> list:
    if isinstance(response, list):
        return response
    for key in candidate_keys:
        value = response.get(key) if isinstance(response, dict) else None
        if isinstance(value, list):
            return value
    data = response.get("data") if isinstance(response, dict) else None
    if isinstance(data, dict):
        for key in candidate_keys:
            value = data.get(key)
            if isinstance(value, list):
                return value
    return []


def _extract_first_value(source: dict, candidate_keys: list[str]):
    if not isinstance(source, dict):
        return None
    for key in candidate_keys:
        if source.get(key):
            return source.get(key)
    return None


def _safe_call(label: str, fn, default=None):
    try:
        return fn()
    except Exception as e:
        print(f"{label}: failed -> {e}")
        return default


def _unique_suffix() -> str:
    return uuid.uuid4().hex[:8]


def _sample_phone() -> str:
    # Produces a 10-digit test number-like string accepted by validators.
    return f"9{str(uuid.uuid4().int)[-9:]}"

def list_test():
    # 1. List agents
    agents = superu.agents.list(limit=5)
    print("Agents:", agents)

    # 2. List folders
    folders = superu.folders.list(per_page=5)
    print("Folders:", folders)

    # 3. List tools
    tools = superu.tools.list(per_page=5)
    print("Tools:", tools)

    # 4. List phone numbers
    phone_numbers = superu.phone_numbers.get_owned()
    print("Phone Numbers:", phone_numbers)

    # 5. List contacts
    contacts = superu.contacts.list(limit=5)
    print("Contacts:", contacts)

    # 6. List audiences
    audiences = superu.audience.list()
    print("Audiences:", audiences)

    # 7. List knowledge bases
    knowledge_bases = superu.knowledge_base.list(limit=5)
    print("Knowledge Bases:", knowledge_bases)

    print("✅ All basic List tests completed successfully")

def get_test():
    # 1. Get agent version (needs one agent + one version)
    agents_response = superu.agents.list(limit=1)
    agents = _extract_list(agents_response, ["agent_list", "agents", "results"])
    if agents:
        agent_id = _extract_first_value(agents[0], ["vapi_assistant_id"])
        if agent_id:
            versions_response = superu.agents.list_versions(agent_id)
            versions = _extract_list(versions_response, ["version_list", "versions", "results"])
            if versions:
                version = _extract_first_value(versions[0], ["version", "name"])
                if version:
                    agent_version = superu.agents.get_version(agent_id, version)
                    print("Agent Version:", agent_version["agent_id"]) # Printing only the agent ID of the version to avoid long output
                else:
                    print("Agent Version: skipped (version field not found)")
            else:
                print("Agent Version: skipped (no versions found)")
        else:
            print("Agent Version: skipped (agent_id not found)")
    else:
        print("Agent Version: skipped (no agents found)")

    # 2. Get tool
    tools_response = superu.tools.list(per_page=1)
    tools = _extract_list(tools_response, ["tool_list", "tools", "results"])
    if tools:
        tool_id = _extract_first_value(tools[0], ["tool_id", "_id", "id"])
        if tool_id:
            tool = superu.tools.get(tool_id)
            print("Tool:", tool)
        else:
            print("Tool: skipped (tool_id not found)")
    else:
        print("Tool: skipped (no tools found)")

    # 3. Get folder
    folders_response = superu.folders.list(per_page=1)
    folders = _extract_list(folders_response, ["folder_list", "folders", "results"])
    if folders:
        folder_id = _extract_first_value(folders[0], ["folder_id", "_id", "id"])
        if folder_id:
            folder = superu.folders.get(folder_id)
            print("Folder:", folder["folder"]["folder_id"]) # Print only the folder ID to avoid long output
        else:
            print("Folder: skipped (folder_id not found)")
    else:
        print("Folder: skipped (no folders found)")

    # 4. Get agents in folder
    if folders:
        folder_id = _extract_first_value(folders[0], ["folder_id", "_id", "id"])
        if folder_id:
            folder_agents = superu.folders.get_agents(folder_id, page=1, per_page=5)
            agents = folder_agents.get("agents", [])
            if agents:
                print("Folder Agents:", agents[0]["vapi_assistant_id"]) # Print only the agent ID of the first agent to avoid long output
            else:
                print("Folder Agents: No agents found in folder")
        else:
            print("Folder Agents: skipped (folder_id not found)")
    else:
        print("Folder Agents: skipped (no folders found)")

    # 5. Get audience
    audiences_response = superu.audience.list()
    audiences = _extract_list(audiences_response, ["audience_list", "audiences", "results"])
    if audiences:
        audience_id = _extract_first_value(audiences[0], ["audience_id", "_id", "id"])
        if audience_id:
            audience = superu.audience.get(audience_id)
            print("Audience:", audience["audience_id"])
        else:
            print("Audience: skipped (audience_id not found)")
    else:
        print("Audience: skipped (no audiences found)")

    # 6. Get audience contacts
    if audiences:
        audience_id = _extract_first_value(audiences[0], ["audience_id", "_id", "id"])
        if audience_id:
            audience_contacts = superu.audience.get_contacts(audience_id, page=1, limit=5)
            print("Audience Contacts:", audience_contacts)
        else:
            print("Audience Contacts: skipped (audience_id not found)")
    else:
        print("Audience Contacts: skipped (no audiences found)")

    # 7. Get knowledge base
    knowledge_bases_response = superu.knowledge_base.list(limit=1)
    knowledge_bases = _extract_list(knowledge_bases_response, ["knowledge_bases", "knowledge_base_list", "results"])
    if knowledge_bases:
        kb_id = _extract_first_value(knowledge_bases[0], ["knowledge_base_id", "kb_uuid", "_id", "id"])
        if kb_id:
            knowledge_base = superu.knowledge_base.get(kb_id)
            print("Knowledge Base uuid:", knowledge_base.get("kb_uuid", "No uuid found"))
        else:
            print("Knowledge Base: skipped (knowledge base ID not found)")
    else:
        print("Knowledge Base: skipped (no knowledge bases found)")

    print("✅ All basic Get tests completed")


def create_test():
    created = {}
    suffix = _unique_suffix()
    print(f"Create test run id: {suffix}")

    # 1. Create folder
    folder = _safe_call(
        "Create Folder",
        lambda: superu.folders.create(
            folder_name=f"test-folder-{suffix}",
            description="SDK smoke test folder"
        )
    )
    if folder:
        created["folder_id"] = _extract_first_value(folder, ["folder_id", "_id", "id"])
        print("Create Folder:", created["folder_id"])

    # 2. Create tool
    tool = _safe_call(
        "Create Tool",
        lambda: superu.tools.create({
            "name": f"sdk-test-tool-{suffix}",
            "description": "SDK smoke test tool",
            "parameters": {
                "type": "object",
                "properties": {
                    "query": {"type": "string", "description": "Input query"}
                },
                "required": ["query"]
            },
            "tool_url": "/api/test-tool",
            "tool_url_domain": "https://example.com",
            "async_": False
        })
    )
    if tool:
        created["tool_id"] = _extract_first_value(tool, ["tool_id", "_id", "id"])
        print("Create Tool:", created["tool_id"])

    # 3. Create audience
    audience = _safe_call(
        "Create Audience",
        lambda: superu.audience.create(
            audience_name=f"sdk-test-audience-{suffix}",
            audience_description="SDK smoke test audience",
            contacts=[
                {
                    "first_name": "SDK",
                    "last_name": "User",
                    "country_code": "+91",
                    "phone_number": _sample_phone(),
                    "email": f"sdk.audience.{suffix}@example.com",
                }
            ]
        )
    )
    if audience:
        created["audience_id"] = _extract_first_value(audience, ["audience_id", "_id", "id"])
        print("Create Audience:", created["audience_id"])

    # 4. Create contact (standalone or with audience)
    contact = _safe_call(
        "Create Contact",
        lambda: superu.contacts.create(
            first_name="SDK",
            last_name="Contact",
            email=f"sdk.contact.{suffix}@example.com",
            country_code="+91",
            phone_number=_sample_phone(),
            audience_id=created.get("audience_id")
        )
    )
    if contact:
        created["contact_id"] = _extract_first_value(contact, ["contact_id", "_id", "id"])
        print("Create Contact:", created["contact_id"])

    # 5. Create knowledge base
    sample_pdf = os.path.join(os.path.dirname(__file__), "sample.pdf")
    if os.path.exists(sample_pdf):
        kb = _safe_call(
            "Create Knowledge Base",
            lambda: superu.knowledge_base.create(
                name=f"sdk-test-kb-{suffix}",
                description="SDK smoke test KB",
                files=[open(sample_pdf, "rb")]
            )
        )
        if kb:
            created["knowledge_base_id"] = _extract_first_value(
                kb, ["knowledge_base_id", "kb_uuid", "_id", "id"]
            )
            created["kb_uuid"] = kb.get("kb_uuid") if isinstance(kb, dict) else None
            print("Create Knowledge Base:", created["knowledge_base_id"])
    else:
        print("Create Knowledge Base: skipped (sample.pdf not found)")

    # 6. Create agent (requires voice id in env)
    test_voice_id = os.getenv("SUPERU_TEST_VOICE_ID")
    if test_voice_id:
        agent = _safe_call(
            "Create Agent",
            lambda: superu.agents.create_agent(
                type="inbound",
                name=f"sdk-test-agent-{suffix}",
                company_name="SuperU",
                assistant_name=f"SDK-{suffix}",
                first_message="Hi! This is an SDK smoke test.",
                system_prompt="You are a helpful test assistant.",
                voice_id=test_voice_id,
                voice_provider="11labs",
                industry="Blank Template",
                useCase="Blank Template",
                knowledge_base=[created["kb_uuid"]] if created.get("kb_uuid") else None
            )
        )
        if agent:
            created["agent_id"] = _extract_first_value(agent, ["agent_id", "vapi_assistant_id", "_id", "id"])
            print("Create Agent:", created["agent_id"])
    else:
        print("Create Agent: skipped (set SUPERU_TEST_VOICE_ID)")

    # 7. Create version (requires created agent + assistant data json in env)
    # assistant_data_json = os.getenv("SUPERU_TEST_ASSISTANT_DATA_JSON")
    # if created.get("agent_id") and assistant_data_json:
    #     import json
    #     assistant_data = json.loads(assistant_data_json)
    #     version_resp = _safe_call(
    #         "Create Version",
    #         lambda: superu.agents.create_version(
    #             agent_id=created["agent_id"],
    #             version=f"sdk-{suffix}",
    #             assistant_data=assistant_data
    #         )
    #     )
    #     if version_resp:
    #         created["version_id"] = _extract_first_value(version_resp, ["version_id", "_id", "id"])
    #         created["version"] = _extract_first_value(version_resp, ["version", "name"])
    #         print("Create Version:", created["version_id"] or created["version"])
    # else:
    #     print("Create Version: skipped (needs created agent and SUPERU_TEST_ASSISTANT_DATA_JSON)")

    # 8. Create outbound call (requires numbers + agent)
    # test_to = os.getenv("SUPERU_TEST_TO")
    # test_from = os.getenv("SUPERU_TEST_FROM")
    # if created.get("agent_id") and test_to:
    #     outbound = _safe_call(
    #         "Create Outbound Call",
    #         lambda: superu.calls.create_outbound_call(
    #             assistant_id=created["agent_id"],
    #             to=test_to,
    #             from_=test_from,
    #             campaign_id=f"sdk-test-{suffix}",
    #             customer_name="SDK Test",
    #             customer_id=f"sdk-{suffix}",
    #             variable_values={"source": "sdk_smoke_test"}
    #         )
    #     )
    #     print("Create Outbound Call:", "ok" if outbound else "failed")
    # else:
    #     print("Create Outbound Call: skipped (needs agent + SUPERU_TEST_TO)")

    # 9. Create Twilio call (requires twilio phone number id + to + agent)
    twilio_phone_number_id = os.getenv("SUPERU_TEST_TWILIO_PHONE_NUMBER_ID")
    if created.get("agent_id") and twilio_phone_number_id and test_to:
        twilio_call = _safe_call(
            "Create Twilio Call",
            lambda: superu.calls.create_twilio_call(
                phoneNumberId=twilio_phone_number_id,
                to_=test_to,
                assistant_id=created["agent_id"],
                additional_payload={"source": "sdk_smoke_test"}
            )
        )
        print("Create Twilio Call:", "ok" if twilio_call else "failed")
    else:
        print("Create Twilio Call: skipped (needs agent + SUPERU_TEST_TWILIO_PHONE_NUMBER_ID + SUPERU_TEST_TO)")

    print("✅ All basic Create tests completed")
    return created


def update_test(created: dict = None):
    created = created or {}
    suffix = _unique_suffix()

    # 1. Update folder
    folder_id = created.get("folder_id")
    if folder_id:
        updated_folder = _safe_call(
            "Update Folder",
            lambda: superu.folders.update(
                folder_id=folder_id,
                folder_name=f"sdk-test-folder-updated-{suffix}",
                description="Updated by SDK smoke test"
            )
        )
        print("Update Folder:", "ok" if updated_folder else "failed")
    else:
        print("Update Folder: skipped (folder_id not available)")

    # 2. Update tool
    tool_id = created.get("tool_id")
    if tool_id:
        updated_tool = _safe_call(
            "Update Tool",
            lambda: superu.tools.update(
                tool_id=tool_id,
                update_data={"description": f"Updated by SDK smoke test {suffix}"}
            )
        )
        print("Update Tool:", "ok" if updated_tool else "failed")
    else:
        print("Update Tool: skipped (tool_id not available)")

    # 3. Update audience
    audience_id = created.get("audience_id")
    if audience_id:
        updated_audience = _safe_call(
            "Update Audience",
            lambda: superu.audience.update(
                audience_id=audience_id,
                audience_name=f"sdk-test-audience-updated-{suffix}",
                audience_description="Updated by SDK smoke test"
            )
        )
        print("Update Audience:", "ok" if updated_audience else "failed")

        add_contact = _safe_call(
            "Add Audience Contact",
            lambda: superu.audience.add_contacts(
                audience_id=audience_id,
                contacts=[{
                    "first_name": "SDK",
                    "last_name": "Added",
                    "country_code": "+91",
                    "phone_number": _sample_phone(),
                    "email": f"sdk.added.{suffix}@example.com"
                }]
            )
        )
        print("Add Audience Contact:", "ok" if add_contact else "failed")
    else:
        print("Update Audience: skipped (audience_id not available)")

    # 4. Update agent name
    agent_id = created.get("agent_id")
    if agent_id:
        updated_agent_name = _safe_call(
            "Update Agent Name",
            lambda: superu.agents.update_name(agent_id, f"sdk-test-agent-updated-{suffix}")
        )
        print("Update Agent Name:", "ok" if updated_agent_name else "failed")
    else:
        print("Update Agent Name: skipped (agent_id not available)")

    # 5. Update version (requires env assistant data json)
    version_id = created.get("version_id")
    if agent_id and version_id:
        assistant_data_json = os.getenv("SUPERU_TEST_ASSISTANT_DATA_JSON")
        if assistant_data_json:
            import json
            assistant_data = json.loads(assistant_data_json)
            updated_version = _safe_call(
                "Update Version",
                lambda: superu.agents.update_version(
                    agent_id=agent_id,
                    version_id=version_id,
                    assistant_data=assistant_data
                )
            )
            print("Update Version:", "ok" if updated_version else "failed")
        else:
            print("Update Version: skipped (set SUPERU_TEST_ASSISTANT_DATA_JSON)")
    else:
        print("Update Version: skipped (agent_id/version_id not available)")

    print("✅ All basic Update tests completed")


def delete_test(created: dict = None):
    created = created or {}

    # 1. Delete audience
    audience_id = created.get("audience_id")
    if audience_id:
        deleted_audience = _safe_call("Delete Audience", lambda: superu.audience.delete(audience_id))
        print("Delete Audience:", "ok" if deleted_audience else "failed")
    else:
        print("Delete Audience: skipped (audience_id not available)")

    # 2. Delete tool
    tool_id = created.get("tool_id")
    if tool_id:
        deleted_tool = _safe_call("Delete Tool", lambda: superu.tools.delete(tool_id))
        print("Delete Tool:", "ok" if deleted_tool else "failed")
    else:
        print("Delete Tool: skipped (tool_id not available)")

    # 3. Delete folder
    folder_id = created.get("folder_id")
    if folder_id:
        deleted_folder = _safe_call("Delete Folder", lambda: superu.folders.delete(folder_id))
        print("Delete Folder:", "ok" if deleted_folder else "failed")
    else:
        print("Delete Folder: skipped (folder_id not available)")

    # 4. Delete agent
    agent_id = created.get("agent_id")
    if agent_id:
        deleted_agent = _safe_call("Delete Agent", lambda: superu.agents.delete(agent_id))
        print("Delete Agent:", "ok" if deleted_agent else "failed")
    else:
        print("Delete Agent: skipped (agent_id not available)")

    print("✅ All basic Delete tests completed")


def miscellaneous_test(created: dict = None):
    created = created or {}

    # 1. Import agents
    imported_agents = _safe_call("Import Agents", lambda: superu.agents.import_agents())
    print("Import Agents:", "ok" if imported_agents else "failed")

    # 2. Assign agent to folder (if both exist)
    if created.get("agent_id") and created.get("folder_id"):
        assign = _safe_call(
            "Assign Agent To Folder",
            lambda: superu.folders.assign_agent(created["agent_id"], created["folder_id"])
        )
        print("Assign Agent To Folder:", "ok" if assign else "failed")
    else:
        print("Assign Agent To Folder: skipped (agent_id/folder_id not available)")

    # 3. Twilio call analysis (requires call uuid)
    twilio_call_uuid = os.getenv("SUPERU_TEST_TWILIO_CALL_UUID")
    if twilio_call_uuid:
        analysis = _safe_call(
            "Analyze Twilio Call",
            lambda: superu.calls.analysis_twilio_call(twilio_call_uuid)
        )
        print("Analyze Twilio Call:", "ok" if analysis else "failed")
    else:
        print("Analyze Twilio Call: skipped (set SUPERU_TEST_TWILIO_CALL_UUID)")



# list_test()
# get_test()
# created_resources = create_test()
# update_test(created_resources)
# miscellaneous_test(created_resources)
# delete_test(created_resources)
