"""abreka exp session — inspect or open native pi stage sessions."""

from __future__ import annotations

import os
import shutil
import subprocess
from pathlib import Path

import click

from abreka.config import find_abreka_dir
from abreka.persistence import load_experiment, normalize_exp_id
from abreka.stage_sessions import stage_session_path


@click.command("session")
@click.argument("exp_id")
@click.argument("stage")
@click.option("--open", "open_session", is_flag=True, help="Open the session directly in pi.")
@click.option("--export", "export_path", type=click.Path(), default=None, help="Export the session to HTML via pi.")
def session_cmd(exp_id: str, stage: str, open_session: bool, export_path: str | None):
    """Print, open, or export the native pi session for a stage."""
    if open_session and export_path is not None:
        raise click.ClickException("--open and --export are mutually exclusive.")

    abreka_dir = find_abreka_dir()
    exp_id = normalize_exp_id(exp_id)
    load_experiment(abreka_dir, exp_id)  # validate experiment exists
    session_path = stage_session_path(abreka_dir, exp_id, stage)
    if not session_path.is_file():
        raise click.ClickException(f"No {stage} session found for experiment {exp_id}.")

    if open_session:
        if not shutil.which("pi"):
            raise click.ClickException(
                "pi not found. Install it: https://github.com/badlogic/pi-mono"
            )
        os.execvp("pi", ["pi", "--session", str(session_path)])
        return

    if export_path is not None:
        output = Path(export_path)
        subprocess.run(["pi", "--export", str(session_path), str(output)], check=True)
        click.echo(f"Exported {stage} session for experiment {exp_id} to {output}")
        return

    click.echo(str(session_path))
