"""Tool: list_orchestration_templates -- discover and search templates in an org."""

import json
from typing import Any, Dict

from ..sfdc.cli import get_default_org, run_soql, SfCliError

TOOL_NAME = "list_orchestration_templates"

TOOL_DEFINITION = {
    "name": TOOL_NAME,
    "description": (
        "List orchestration process templates in a Salesforce org. "
        "Use this to discover available template names before fetching, "
        "or to validate that a template name exists. "
        "Returns template names and IDs."
    ),
    "inputSchema": {
        "type": "object",
        "properties": {
            "org_alias": {
                "type": "string",
                "description": (
                    "Salesforce org alias (e.g. 'itxdevpro', 'sit p3'). "
                    "DO NOT ask the user for this -- if they don't mention an org, "
                    "simply omit this parameter and the tool will automatically use "
                    "the workspace's default target-org from Salesforce CLI."
                ),
            },
            "search_term": {
                "type": "string",
                "description": (
                    "Filter templates whose name contains this text (case-insensitive). "
                    "For example, 'Internet CPE' would match 'Internet CPE Terminate Flow (Subprocess)'. "
                    "If omitted, returns ALL templates in the org."
                ),
            },
        },
        "required": [],
    },
}


async def execute(arguments: Dict[str, Any]) -> str:
    """Execute the list_orchestration_templates tool."""
    org_alias = arguments.get("org_alias") or None
    search_term = arguments.get("search_term")

    soql = "SELECT Id, Name FROM CSPOFA__Orchestration_Process_Template__c"
    if search_term:
        safe_term = search_term.replace("'", "\\'")
        soql += f" WHERE Name LIKE '%{safe_term}%'"
    soql += " ORDER BY Name ASC"

    try:
        result = run_soql(soql, org_alias=org_alias)
    except SfCliError as e:
        return json.dumps({
            "success": False,
            "error": str(e),
            "hint": (
                "Ensure the org is authorized via 'sf org login web' and has the "
                "CloudSense Orchestration package installed."
            ),
        }, indent=2)

    records = result.get("records", [])
    templates = [
        {"id": r.get("Id"), "name": r.get("Name")}
        for r in records
        if r.get("Name")
    ]

    resolved_org = org_alias or get_default_org() or "(sf CLI default)"

    return json.dumps({
        "success": True,
        "org": resolved_org,
        "total_count": len(templates),
        "search_term": search_term,
        "templates": templates,
    }, indent=2)
