"""{{ experiment_description }}

This is an interactive terminal UI experiment using ExperimentTUI.

The TUI provides:
- Real-time status display of the experiment
- A log viewer panel showing experiment events
- Interactive controls to pause, resume, and cancel the experiment
- Automatic experiment lifecycle management

Generated by: madsci new experiment --modality tui
Template version: {{ template_version }}
"""

from typing import Any

from madsci.common.types.experiment_types import ExperimentDesign
from madsci.experiment_application import ExperimentTUI, ExperimentTUIConfig


class {{ experiment_name | pascal_case }}TUIExperiment(ExperimentTUI):
    """{{ experiment_description }}

    This experiment uses the ExperimentTUI modality, which provides an
    interactive terminal user interface for experiment control.

    TUI Features:
        - Status display: Shows current experiment state in real time.
        - Log viewer: Streams experiment log events as they occur.
        - Pause/Resume: Pause the experiment at the next check point and
          resume when ready.
        - Cancel: Cancel the experiment gracefully via the TUI controls.

    To run this experiment:
        python {{ experiment_name }}_tui.py

    Or programmatically:
        from {{ experiment_name }}_tui import {{ experiment_name | pascal_case }}TUIExperiment
        {{ experiment_name | pascal_case }}TUIExperiment().run_tui()
    """

    # Define the experiment design
    experiment_design = ExperimentDesign(
        experiment_name="{{ experiment_name | replace('_', ' ') | title }}",
        experiment_description="{{ experiment_description }}",
    )

    def run_experiment(self, *args: Any, **kwargs: Any) -> dict[str, Any]:
        """Execute the experiment logic within the TUI.

        This method is called by the TUI when the user starts the experiment.
        It runs inside the manage_experiment() context, so:
        - The experiment is automatically started before this runs
        - The experiment is automatically ended after this completes
        - Exceptions are logged and the experiment marked as failed

        Use self.check_experiment_status() periodically in loops to allow the
        TUI to pause or cancel the experiment between iterations.

        Available clients (from ExperimentBase):
        - self.workcell_client: Run workflows
        - self.experiment_client: Manage experiment state
        - self.data_client: Store and retrieve data
        - self.resource_client: Track resources
        - self.event_client / self.logger: Log events

        Args:
            *args: Positional arguments from run() or config.run_args.
            **kwargs: Keyword arguments from run() or config.run_kwargs.

        Returns:
            Dictionary containing experiment results.
        """
        # Log experiment start
        self.logger.info(
            "Starting experiment: {{ experiment_name }}",
            experiment_name="{{ experiment_name }}",
        )

        # ==========================================
        # YOUR EXPERIMENT LOGIC HERE
        # ==========================================

        # Example: Run a workflow
        # result = self.workcell_client.run_workflow(
        #     workflow_name="my_workflow",
        #     parameters={"param1": "value1"},
        # )

        # Example: Store data
        # self.data_client.store_data(
        #     name="experiment_output",
        #     data={"key": "value"},
        # )

        # Example: Iterative experiment with pause/cancel support.
        # Call self.check_experiment_status() in each iteration so the TUI
        # can pause or cancel the experiment between steps.
        num_steps = 5
        results: list[dict[str, Any]] = []
        for step in range(num_steps):
            # Check for pause/cancel requests from the TUI
            self.check_experiment_status()

            self.logger.info(
                f"Processing step {step + 1}/{num_steps}",
                step=step + 1,
                total_steps=num_steps,
            )

            # Placeholder step result
            step_result = {
                "step": step + 1,
                "status": "completed",
            }
            results.append(step_result)

        # ==========================================
        # END EXPERIMENT LOGIC
        # ==========================================

        result = {
            "status": "completed",
            "message": "Experiment finished successfully",
            "steps_completed": len(results),
            "data": results,
        }

        self.logger.info(
            "Experiment completed",
            result=result,
        )

        return result


def main() -> None:
    """Main entry point for the TUI experiment.

    Launches the interactive terminal UI for experiment control.
    """
    {{ experiment_name | pascal_case }}TUIExperiment().run_tui()


if __name__ == "__main__":
    main()
