"""
cli.py — czipeak command-line interface.

Entry point registered in pyproject.toml:
    czipeak = "czipeak.cli:main"
"""

from __future__ import annotations

import argparse
import csv
import sys
from pathlib import Path

from .reader import read_czi, _extract_timestamp_list, _load_xml
from .display import print_metadata


def main() -> None:
    parser = argparse.ArgumentParser(
        prog="czipeak",
        description="Peek into Zeiss CZI files — temporal and Z-stack metadata at a glance.",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
examples:
  czipeak  experiment.czi
  czipeak  experiment.czi --verbose
  czipeak  experiment.czi --csv
  czipeak  experiment.czi --csv my_timestamps.csv
        """,
    )
    parser.add_argument("czi_file", help="Path to the .czi file")
    parser.add_argument(
        "-v", "--verbose",
        action="store_true",
        help="Print all per-frame timestamps (when available)",
    )
    parser.add_argument(
        "--csv",
        metavar="OUTPUT",
        nargs="?",
        const="",       # empty → auto-name next to CZI
        default=None,
        help="Export timestamps to CSV (auto-named if no path given)",
    )
    args = parser.parse_args()

    path = Path(args.czi_file)
    if not path.exists():
        print(f"✗  File not found: {args.czi_file}", file=sys.stderr)
        sys.exit(1)

    try:
        meta = read_czi(str(path))
    except ImportError as exc:
        print(f"✗  {exc}", file=sys.stderr)
        sys.exit(1)
    except Exception as exc:
        print(f"✗  Failed to read CZI: {exc}", file=sys.stderr)
        sys.exit(1)

    # Per-frame timestamps (legacy schema — empty list for modern files)
    try:
        root = _load_xml(str(path))
        timestamps = _extract_timestamp_list(root)
    except Exception:
        timestamps = []

    print_metadata(meta, verbose=args.verbose, timestamps=timestamps or None)

    # Optional CSV export
    if args.csv is not None:
        if timestamps:
            out_path = Path(args.csv) if args.csv else path.with_suffix(".timestamps.csv")
            with open(out_path, "w", newline="") as f:
                writer = csv.writer(f)
                writer.writerow(["frame", "t_s", "dt_s"])
                for i, t in enumerate(timestamps):
                    dt = timestamps[i] - timestamps[i-1] if i > 0 else ""
                    writer.writerow([i, t, dt])
            print(f"  Timestamps saved → {out_path}")
        else:
            print("  ⚠  No per-frame timestamps available for CSV export.")


if __name__ == "__main__":
    main()
