"""Hook configuration loading."""

from __future__ import annotations

import json
import os
from pathlib import Path
from typing import List

from promethian.hooks.types import HookConfig, HookEvent


# Default hooks config locations
HOOKS_CONFIG_PATHS = [
    Path.home() / ".promethian" / "hooks.json",  # User config
    Path(".promethian") / "hooks.json",  # Project config
]


def load_hooks(
    config_paths: list[Path] | None = None,
) -> list[HookConfig]:
    """
    Load hook configurations from config files.

    Loads from default paths if not specified:
    - ~/.promethian/hooks.json (user config)
    - .promethian/hooks.json (project config)

    Project hooks are loaded after user hooks (can override).

    Args:
        config_paths: Optional list of paths to load from

    Returns:
        List of HookConfig objects
    """
    paths = config_paths or HOOKS_CONFIG_PATHS
    hooks: list[HookConfig] = []

    for path in paths:
        if path.exists():
            try:
                with open(path, "r") as f:
                    data = json.load(f)

                for hook_data in data.get("hooks", []):
                    try:
                        hook = HookConfig.from_dict(hook_data)
                        if hook.enabled:
                            # Expand ~ in script path
                            hook.script = os.path.expanduser(hook.script)
                            hooks.append(hook)
                    except (KeyError, ValueError) as e:
                        # Skip invalid hook configs
                        print(f"Warning: Invalid hook config in {path}: {e}")
                        continue

            except json.JSONDecodeError as e:
                print(f"Warning: Failed to parse hooks config {path}: {e}")
            except Exception as e:
                print(f"Warning: Error loading hooks from {path}: {e}")

    return hooks


def get_hooks_for_event(
    hooks: list[HookConfig],
    event: HookEvent,
    tool_name: str | None = None,
) -> list[HookConfig]:
    """
    Filter hooks to those matching an event and optionally a tool.

    Args:
        hooks: All loaded hooks
        event: The event type to filter for
        tool_name: Optional tool name to filter for

    Returns:
        List of matching HookConfig objects
    """
    matching = []

    for hook in hooks:
        if hook.event != event:
            continue

        # If hook specifies a tool, only match that tool
        if hook.tool is not None:
            if tool_name is None or hook.tool != tool_name:
                continue

        matching.append(hook)

    return matching


def save_hooks(
    hooks: list[HookConfig],
    path: Path | None = None,
) -> None:
    """
    Save hook configurations to a file.

    Args:
        hooks: List of hook configs to save
        path: Path to save to (defaults to user config)
    """
    path = path or HOOKS_CONFIG_PATHS[0]
    path.parent.mkdir(parents=True, exist_ok=True)

    data = {
        "hooks": [hook.to_dict() for hook in hooks]
    }

    with open(path, "w") as f:
        json.dump(data, f, indent=2)
