"""Operator registry - single source of truth for transform metadata."""

from __future__ import annotations

import json
from pathlib import Path
from typing import Dict, List, Optional


class OperatorRegistry:
    """Registry of all transform operations with metadata."""

    def __init__(self) -> None:
        registry_path = Path(__file__).parent / "registry.json"
        with registry_path.open(encoding="utf-8") as handle:
            data = json.load(handle)
        self.operations = {op["id"]: op for op in data.get("operations", [])}

    def get(self, op_id: str) -> Optional[Dict]:
        """Get operation metadata by ID."""
        return self.operations.get(op_id)

    def list_all(self) -> List[Dict]:
        """Get all operations."""
        return list(self.operations.values())

    def list_ui_exposed(self) -> List[Dict]:
        """Get only UI-exposed operations."""
        return [op for op in self.operations.values() if op.get("ui_exposed")]

    def list_formula_exposed(self) -> List[Dict]:
        """Get only formula-exposed operations."""
        return [op for op in self.operations.values() if op.get("formula_exposed")]

    def list_formula_exposed_active(self) -> List[Dict]:
        """Get formula-exposed operations that are not deprecated."""
        return [
            op
            for op in self.operations.values()
            if op.get("formula_exposed") and not op.get("deprecated")
        ]

    def validate_op(self, op_id: str) -> bool:
        """Check if operation exists."""
        return op_id in self.operations

    def is_deprecated(self, op_id: str) -> bool:
        """Check if an operation has been deprecated."""
        op = self.get(op_id)
        return op.get("deprecated", False) if op else False

    def get_deprecation_note(self, op_id: str) -> Optional[str]:
        """Return the deprecation note when available."""
        op = self.get(op_id)
        return op.get("deprecation_note") if op else None

    def get_supported_operations(self) -> set:
        """Get set of all operation IDs (replaces hardcoded SUPPORTED_OPERATIONS)."""
        return set(self.operations.keys())

    def get_output_count(self, op_id: str) -> int:
        """Get number of output columns for an operation."""
        op = self.get(op_id)
        return op.get("outputs", 1) if op else 1

    def get_output_headers(self, op_id: str) -> List[str]:
        """Get output column headers for an operation."""
        op = self.get(op_id)
        return op.get("output_headers", []) if op else []


# Singleton instance
registry = OperatorRegistry()
