"""Handler for install_symbol command.

Atomic command that decodes a base64-encoded .kicad_sym file, merges its
symbol(s) into the single global Adom library (Adom.kicad_sym), and
optionally opens the Symbol Editor.

All symbols installed by Adom live in one KiCad symbol library called "Adom".
This library is created automatically on first use and registered in the
global sym-lib-table.  Subsequent installs simply add/update symbols inside
that same file -- no need to create new libraries or restart KiCad for
library table changes.

Steps:
1. Decode base64 file content
2. Merge symbol(s) into Adom.kicad_sym (creates library if needed)
3. Optionally open Symbol Editor with the symbol loaded
"""

import base64
import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).parent.parent))

from adom_library import add_symbol, ADOM_LIB_NAME
from handlers.open_symbol_editor import handle_open_symbol_editor


def handle_install_symbol(kicad_info: dict, args: dict) -> dict:
    """Install a KiCad symbol from base64-encoded file content.

    Args:
        kicad_info: KiCad detection info dict.
        args: Dict with:
            - fileName (required): Original filename (e.g. "BQ76952.kicad_sym")
            - fileContent (required): Base64-encoded .kicad_sym file content
            - symbolName (optional): Specific symbol to open in the editor
            - openEditor (optional): Whether to open Symbol Editor (default: true)

    Returns:
        Dict with:
            - success: bool
            - installedPath: path to Adom.kicad_sym
            - symbolNames: list of symbol names added/updated
            - libraryName: always "Adom"
            - editorOpened: bool
            - output: human-readable summary
            - error: error message (only if success is false)
    """
    if not kicad_info.get("installed"):
        return {
            "success": False,
            "error": "KiCad not installed",
            "_hint": "Report to the user and ask them to install KiCad from https://www.kicad.org/download/, then retry.",
        }

    file_name = args.get("fileName", "")
    file_content = args.get("fileContent", "")
    symbol_name = args.get("symbolName", "")
    quiet_install = args.get("quietInstall", False)
    open_editor = False if quiet_install else args.get("openEditor", True)

    if not file_name:
        return {"success": False, "error": "No fileName specified"}
    if not file_content:
        return {"success": False, "error": "No fileContent specified"}

    # --- Step 1: Decode the file ---

    try:
        decoded = base64.b64decode(file_content)
        symbol_text = decoded.decode("utf-8")
    except Exception as e:
        return {"success": False, "error": f"Failed to decode fileContent: {e}"}

    # --- Step 2: Merge into Adom.kicad_sym ---

    result = add_symbol(kicad_info, symbol_text)

    if not result.get("success"):
        return {"success": False, "error": result.get("error", "Unknown error")}

    added_names = result.get("added", [])
    lib_path = result.get("lib_path", "")

    # --- Step 3: Optionally open Symbol Editor ---

    editor_opened = False
    editor_output = ""

    if open_editor and added_names:
        # Search for the specific symbol, or the first one added
        search_name = symbol_name or added_names[0]
        editor_result = handle_open_symbol_editor(kicad_info, {
            "symbolName": search_name,
            "libraryName": ADOM_LIB_NAME,
        })
        editor_opened = editor_result.get("success", False)
        editor_output = editor_result.get("output", editor_result.get("error", ""))

    # --- Build result ---

    output_parts = [
        f"Symbol(s) {', '.join(added_names)} added to '{ADOM_LIB_NAME}' library"
    ]
    if editor_opened:
        output_parts.append(f"Symbol Editor: {editor_output}")
    elif open_editor:
        output_parts.append(f"Symbol Editor: {editor_output}")

    return {
        "success": True,
        "output": " | ".join(output_parts),
        "installedPath": lib_path,
        "symbolNames": added_names,
        "libraryName": ADOM_LIB_NAME,
        "editorOpened": editor_opened,
    }