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

import json
from typing import Any, Dict

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

TOOL_NAME = "list_orchestration_templates"

TOOL_DEFINITION = {
    "name": TOOL_NAME,
    "description": (
        "Show or list CloudSense orchestration process template names in a Salesforce org. "
        "Use ONLY when the user wants to browse, show, list, search, or check what templates "
        "exist. Returns template names and IDs only (does NOT download template content -- "
        "use fetch_orchestration_templates for that). "
        "Do NOT use this tool when the user says 'get', 'fetch', 'download', or 'export' -- "
        "use fetch_orchestration_templates instead. "
        "Org is auto-resolved from session or workspace default if not specified."
    ),
    "inputSchema": {
        "type": "object",
        "properties": {
            "org_alias": {
                "type": "string",
                "description": (
                    "Salesforce org alias or partial hint (e.g. 'itxdevpro', 'devpro', 'sit p3'). "
                    "Partial names are fuzzy-matched against authenticated orgs. "
                    "OMIT this parameter if the user did not mention a specific org -- "
                    "the tool will automatically use the session org or workspace default."
                ),
            },
            "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_resolution = resolve_org(arguments.get("org_alias") or None)

    if "error" in org_resolution:
        return json.dumps({
            "success": False,
            "error": org_resolution["error"],
            "candidates": org_resolution.get("candidates", []),
        }, indent=2)

    org_alias = org_resolution["org_alias"]
    org_source = org_resolution["org_source"]

    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),
            "org": org_alias,
            "org_source": org_source,
        }, indent=2)

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

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