"""
Write-enabled MCP tools for Salesforce apply operations.
"""

from __future__ import annotations

from pathlib import Path
from typing import Any, Callable, Dict, List, Tuple

from g_gremlin import sfdc_metadata_pack
from g_gremlin import sfdc_pack

ToolTuple = Tuple[str, Callable[..., Dict[str, Any]], str]


def sfdc_metadata_pack_apply(
    pack_dir: str,
    plan_hash: str,
    target: str | None = None,
    plan_path: str | None = None,
    replan: bool = False,
    check_only: bool = False,
) -> Dict[str, Any]:
    if not str(plan_hash or "").strip():
        raise ValueError("plan_hash is required for sfdc.metadata_pack.apply")
    resolved_plan_path = Path(plan_path) if plan_path else None
    result = sfdc_metadata_pack.apply_pack(
        Path(pack_dir),
        org_alias=target,
        plan_path=resolved_plan_path,
        yes=True,
        replan=replan,
        check_only=check_only,
        expected_plan_hash=plan_hash,
    )
    return result.to_dict()


def sfdc_pack_apply(
    pack_dir: str,
    plan_hash: str,
    target: str | None = None,
    plan_path: str | None = None,
    replan: bool = False,
) -> Dict[str, Any]:
    if not str(plan_hash or "").strip():
        raise ValueError("plan_hash is required for sfdc.pack.apply")
    resolved_plan_path = Path(plan_path) if plan_path else None
    result = sfdc_pack.apply_pack(
        Path(pack_dir),
        org_alias=target,
        plan_path=resolved_plan_path,
        yes=True,
        replan=replan,
        expected_plan_hash=plan_hash,
    )
    return result.to_dict()


def get_tools() -> List[ToolTuple]:
    return [
        ("sfdc.metadata_pack.apply", sfdc_metadata_pack_apply, "Apply metadata pack changes (requires plan_hash)."),
        ("sfdc.pack.apply", sfdc_pack_apply, "Apply data pack changes (requires plan_hash)."),
    ]
