"""connect_lma -- Authorize the CloudSense License Management Portal.

Entry point for the workflow. Checks if the LMA org is already
authorized, opens browser login if not, and saves connection info
to assessment.json.
"""

import logging
from typing import Any

from ..utils import sf_cli, state

logger = logging.getLogger(__name__)

DEFAULT_ALIAS = "cs-lma"
DEFAULT_LOGIN_URL = "https://login.salesforce.com"

TOOL_DEFINITION = {
    "name": "connect_lma",
    "description": (
        "Authorize the CloudSense License Management Portal. "
        "This is the FIRST tool to call for any customer inquiry. "
        "Checks if the LMA org is already authorized, opens browser "
        "login if not, and saves connection info to state."
    ),
    "inputSchema": {
        "type": "object",
        "properties": {
            "org_alias": {
                "type": "string",
                "description": (
                    "Alias for the LMA org. Defaults to 'cs-lma'. "
                    "If already authorized under this alias, login is skipped."
                ),
            },
            "instance_url": {
                "type": "string",
                "description": (
                    "Salesforce login URL. Defaults to "
                    "'https://login.salesforce.com'. Override for custom domains."
                ),
            },
            "working_directory": {
                "type": "string",
                "description": "Workspace directory. The AI passes this automatically.",
            },
        },
        "required": [],
    },
}


def _validate_org(alias: str) -> dict[str, Any] | None:
    """Check if an org is authorized and accessible."""
    try:
        data = sf_cli.display_org(alias)
        return data.get("result", {})
    except sf_cli.SfCliError:
        return None


async def run(arguments: dict[str, Any]) -> str:
    """Execute the connect_lma tool."""
    state.set_working_dir(arguments.get("working_directory"))

    sf_check = sf_cli.check_sf_installed()
    if not sf_check["installed"]:
        return (
            "## BLOCKER: Salesforce CLI not found\n\n"
            "Install from: https://developer.salesforce.com/tools/salesforcecli\n"
            "Then call connect_lma again."
        )

    alias = arguments.get("org_alias") or DEFAULT_ALIAS
    instance_url = arguments.get("instance_url")

    org_info = _validate_org(alias)

    if not org_info:
        login_url = instance_url or DEFAULT_LOGIN_URL
        try:
            sf_cli.run_sf(
                f"org login web --alias {alias} --instance-url {login_url}",
                timeout=300, json_output=False,
            )
        except sf_cli.SfCliError as e:
            return (
                f"## BLOCKER: Login failed\n\n"
                f"Error: {e}\n\n"
                f"Run manually if browser didn't open:\n"
                f"```\nsf org login web --alias {alias} --instance-url {login_url}\n```"
            )

        org_info = _validate_org(alias)
        if not org_info:
            return (
                "## BLOCKER: Login succeeded but validation failed\n\n"
                "Call connect_lma again to retry."
            )

    username = org_info.get("username", "unknown")
    org_id = org_info.get("id", "unknown")
    instance = org_info.get("instanceUrl", "unknown")

    state.update(
        lma_org_alias=alias,
        lma_org_username=username,
        lma_org_id=org_id,
        lma_instance_url=instance,
    )

    return (
        f"## LMA Connected\n\n"
        f"- **Alias:** {alias}\n"
        f"- **Username:** {username}\n"
        f"- **Org ID:** {org_id}\n"
        f"- **Instance:** {instance}\n"
    )
