"""eWAL CLI entry point.

Usage:
    ewal repl counter.fst          # Interactive REPL
    ewal run analysis.py counter.fst  # Run script
    ewal info counter.fst          # Trace info
    ewal -c "..." counter.fst      # One-liner
"""

import argparse
import sys


def main():
    parser = argparse.ArgumentParser(
        prog="ewal",
        description="Embedded Waveform Analysis Library",
    )
    subparsers = parser.add_subparsers(dest="command")

    # ewal info <trace>
    info_parser = subparsers.add_parser("info", help="Show trace information")
    info_parser.add_argument("trace", help="Path to trace file")

    # ewal repl <trace>
    repl_parser = subparsers.add_parser("repl", help="Interactive REPL")
    repl_parser.add_argument("trace", nargs="?", help="Path to trace file")

    # ewal run <script> <trace>
    run_parser = subparsers.add_parser("run", help="Run analysis script")
    run_parser.add_argument("script", help="Python script to run")
    run_parser.add_argument("trace", nargs="?", help="Path to trace file")

    # ewal -c "code" <trace>
    parser.add_argument("-c", metavar="CODE", help="Execute one-liner code")
    parser.add_argument("args", nargs="*", help="Positional arguments (trace files)")

    parsed = parser.parse_args()

    if parsed.c:
        _run_oneliner(parsed.c, parsed.args)
    elif parsed.command == "info":
        _show_info(parsed.trace)
    elif parsed.command == "repl":
        _start_repl(parsed.trace)
    elif parsed.command == "run":
        _run_script(parsed.script, parsed.trace)
    else:
        parser.print_help()


def _show_info(path: str):
    import ewal

    t = ewal.load(path)
    print(f"Trace: {path}")
    print(f"Max index: {t.max_index}")
    print(f"Signals ({len(t.signals)}):")
    for sig in sorted(t.signals):
        w = t.width(sig)
        print(f"  {sig} [{w-1}:0]" if w > 1 else f"  {sig}")
    print(f"Scopes ({len(t.scopes)}):")
    for scope in sorted(t.scopes):
        print(f"  {scope}")


def _start_repl(path: str = None):
    import ewal

    ns = {"ewal": ewal}
    if path:
        t = ewal.load(path)
        ns["t"] = t
        ns["load"] = ewal.load
        ns["find"] = t.find
        print(f"Loaded: {path} (max_index={t.max_index}, {len(t.signals)} signals)")
        print("Trace available as 't'")

    try:
        from IPython import start_ipython
        start_ipython(argv=[], user_ns=ns)
    except ImportError:
        import code
        code.interact(local=ns, banner="eWAL REPL (use IPython for better experience)")


def _run_script(script: str, trace: str = None):
    import ewal

    ns = {"ewal": ewal, "load": ewal.load}
    if trace:
        ns["t"] = ewal.load(trace)
        ns["args"] = [trace]
    else:
        ns["args"] = []

    with open(script) as f:
        exec(compile(f.read(), script, "exec"), ns)


def _run_oneliner(code: str, args: list[str]):
    import ewal

    ns = {"ewal": ewal, "load": ewal.load, "args": args}
    if args:
        ns["t"] = ewal.load(args[0])
        ns["find"] = ns["t"].find
    exec(code, ns)


if __name__ == "__main__":
    main()
