"""
pyxTrace command-line interface

Usage examples
--------------

# Original depth, live dashboard
pyxtrace examples/fibonacci.py --dash

# Faster: skip std-lib lines but keep line-level detail
pyxtrace examples/fibonacci.py --mode perf --dash

# Ultra-fast for teaching: call/return only
pyxtrace examples/fibonacci.py --mode demo
"""
from __future__ import annotations

import enum
from pathlib import Path
import sys
import typer

from pyxtrace import core
from pyxtrace import replay as _replay_module


app = typer.Typer(
    add_completion=False,
    help="pyxTrace – interactive Python execution visualiser",
)

app.add_typer(_replay_module.app, name="replay", help="Replay a recorded trace")

# -------------------------------------------------------------------- #
# Enum used for --mode
# -------------------------------------------------------------------- #
class TraceMode(str, enum.Enum):
    full = "full"      # original behaviour
    perf = "perf"      # skip std-lib / built-ins
    demo = "demo"      # call + return events only


# -------------------------------------------------------------------- #
# Single command (“classic”) – no sub-commands required
# -------------------------------------------------------------------- #
@app.callback(invoke_without_command=True,
               context_settings={"allow_extra_args": True,
                                "ignore_unknown_options": True})
def run(
    ctx: typer.Context,
    script: Path = typer.Argument(..., exists=True, readable=True, resolve_path=True),
    mode: TraceMode = typer.Option(
        TraceMode.full, "--mode", "-m", help="Tracing depth: full | perf | demo"
    ),
    log: Path | None = typer.Option(
        None,
        "--log",
        "-o",
        help="Optional JSONL output file (default ./pyxtrace-<ts>.jsonl)",
    ),
    dash: bool = typer.Option(
        False, "--dash", help="Launch live dashboard after tracing finishes"
    )
):
    
    if script is None:
        # user typed just `pyxtrace` or wants help
        if ctx.invoked_subcommand is None:
            typer.echo(ctx.get_help())
        return
    
    """
    Trace *SCRIPT* and stream events live to a JSONL log.\n
    All arguments after “--” are forwarded to the traced program.
    """
    # Forward any user args (after --) to the target script
    idx = sys.argv.index("--") + 1 if "--" in sys.argv else len(sys.argv)
    sys.argv = [str(script)] + sys.argv[idx:]

    core.TraceSession(
        script_path=script,
        log_path=log,
        mode=mode.value,
        dash=dash,
    ).run()


# -------------------------------------------------------------------- #
# Console-script entry-point generated by pip -e .
# -------------------------------------------------------------------- #
def main() -> None:  # noqa: D401 – imperative (“Run …”)
    app()


if __name__ == "__main__":  # pragma: no cover
    main()
