"""
Scaffold plugin command.
"""

from __future__ import annotations

from pathlib import Path

import click


_PLUGIN_TEMPLATES = {
    "monitor": """from __future__ import annotations

import threading
from typing import Any, Dict, List

from metamorphic_guard.monitoring import Monitor, MonitorContext, MonitorRecord


class {name}(Monitor):
    \"\"\"Custom monitor generated by `metamorphic-guard scaffold-plugin`.
    
    TODO: Customize this monitor to track specific metrics or behaviors.
    \"\"\"

    PLUGIN_METADATA = {{
        \"name\": \"{name}\",
        \"version\": \"0.1.0\",
        \"description\": \"Describe the behaviour monitored by {name}.\",
    }}

    def __init__(self, **kwargs: Any) -> None:
        super().__init__()
        # TODO: Initialize monitor state (counters, lists, etc.)
        self._lock = threading.Lock()
        self._data: Dict[str, List[Any]] = {{"baseline": [], "candidate": []}}

    def start(self, context: MonitorContext) -> None:
        \"\"\"Called when evaluation starts.\"\"\"
        super().start(context)
        # TODO: Initialize monitoring based on context

    def record(self, record: MonitorRecord) -> None:
        \"\"\"Record a single execution result.\"\"\"
        with self._lock:
            role = record.role
            result = record.result
            
            # TODO: Extract and store relevant metrics from record
            # Example:
            # if record.success:
            #     self._data[role].append(some_metric)
            pass

    def finalize(self) -> Dict[str, Any]:
        \"\"\"Return aggregated monitor output with summary and alerts.\"\"\"
        with self._lock:
            summary: Dict[str, Dict[str, Any]] = {{}}
            alerts: List[Dict[str, Any]] = []
            
            # TODO: Compute summary statistics
            for role, values in self._data.items():
                summary[role] = {{
                    \"count\": len(values),
                    # Add more summary metrics here
                }}
            
            # TODO: Generate alerts based on thresholds or anomalies
            # Example:
            # if some_condition:
            #     alerts.append({{
            #         \"severity\": \"warning\",
            #         \"message\": \"Description of the issue\",
            #     }})
            
            return {{
                \"id\": self.identifier(),
                \"type\": \"{name_lower}\",
                \"summary\": summary,
                \"alerts\": alerts,
            }}
""",
    "dispatcher": """from __future__ import annotations

from typing import Any, Dict, Sequence, Tuple

from metamorphic_guard.dispatch import Dispatcher, RunCase
from metamorphic_guard.monitoring import Monitor


class {name}(Dispatcher):
    \"\"\"Custom dispatcher generated by `metamorphic-guard scaffold-plugin`.\"\"\"

    PLUGIN_METADATA = {{
        \"name\": \"{name}\",
        \"version\": \"0.1.0\",
        \"description\": \"Describe the dispatch strategy implemented by {name}.\",
    }}

    def __init__(self, workers: int = 1, config: Dict[str, Any] | None = None):
        super().__init__(workers, kind=\"{name_lower}\")
        self.config = config or {{}}

    def execute(
        self,
        *,
        test_inputs: Sequence[Tuple[Any, ...]],
        run_case: RunCase,
        role: str,
        monitors: Sequence[Monitor] | None = None,
        call_spec: Dict[str, Any] | None = None,
    ):
        return [run_case(i, args) for i, args in enumerate(test_inputs)]
""",
}


@click.command("scaffold-plugin")
@click.option("--name", required=True, help="Python class name for the plugin.")
@click.option(
    "--kind",
    type=click.Choice(["monitor", "dispatcher"], case_sensitive=False),
    default="monitor",
    show_default=True,
    help="Type of plugin scaffold to generate.",
)
@click.option(
    "--path",
    type=click.Path(dir_okay=False, writable=True, path_type=Path),
    default=None,
    help="File to write (defaults to <name>.py).",
)
def scaffold_plugin(name: str, kind: str, path: Path | None) -> None:
    """Generate a starter plugin implementation."""

    target = path or Path(f"{name.lower()}.py")
    if target.exists():
        raise click.ClickException(f"Target file {target} already exists.")

    template = _PLUGIN_TEMPLATES[kind.lower()]
    target.write_text(template.format(name=name, name_lower=name.lower()), encoding="utf-8")
    click.echo(f"Plugin scaffold written to {target}")

