from __future__ import annotations

import argparse

from neurobyte.export import ExportOptions, export_notebook


def _parse_cell_range(value: str) -> list[int]:
    """Parse cell range like '1-5' or '1,3,5' into list of indices."""
    indices: list[int] = []
    for part in value.split(","):
        part = part.strip()
        if "-" in part:
            start, end = part.split("-", 1)
            indices.extend(range(int(start.strip()), int(end.strip()) + 1))
        else:
            indices.append(int(part))
    return sorted(set(indices))


def main() -> None:
    parser = argparse.ArgumentParser(prog="neurobyte")
    sub = parser.add_subparsers(dest="cmd", required=True)

    exp = sub.add_parser("export", help="Export a notebook to neurobyte format.")
    exp.add_argument("notebook", type=str, help="Path to .ipynb")
    exp.add_argument("-o", "--out", type=str, default=None, help="Output file path")
    exp.add_argument(
        "--no-redact",
        action="store_true",
        help="Disable automatic redaction of secrets",
    )
    exp.add_argument(
        "--redact-pattern",
        action="append",
        dest="redact_patterns",
        metavar="REGEX",
        help="Additional regex pattern to redact (can be repeated)",
    )
    exp.add_argument(
        "--cells",
        type=str,
        default=None,
        metavar="RANGE",
        help="Cell range to export, e.g., '1-5' or '1,3,5'",
    )
    exp.add_argument(
        "--include-markdown",
        action="store_true",
        help="Include markdown cells in output",
    )
    exp.add_argument(
        "--json",
        action="store_true",
        help="Output in JSON format instead of text",
    )

    args = parser.parse_args()

    if args.cmd == "export":
        # Parse cell indices
        cell_indices = None
        if args.cells:
            cell_indices = _parse_cell_range(args.cells)

        opts = ExportOptions(
            redact_secrets=not args.no_redact,
            extra_redact_patterns=args.redact_patterns or [],
            cell_indices=cell_indices,
            include_markdown=args.include_markdown,
            output_format="json" if args.json else "txt",
        )
        out = export_notebook(args.notebook, args.out, options=opts)
        print(str(out))
