"""Command-line interface for Dataset Inspector."""

from __future__ import annotations

import argparse
import sys

from dataset_inspector.analyzer import analyze, load_csv
from dataset_inspector.report import export_json, print_report
from dataset_inspector.utils import setup_logging


def build_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(
        prog="dataset-inspector",
        description="Analyze a CSV dataset and detect common data issues before ML training.",
    )
    parser.add_argument(
        "-i", "--input",
        required=True,
        help="Path to the CSV file to analyze.",
    )
    parser.add_argument(
        "-t", "--target",
        default=None,
        help="Name of the target column (for class-imbalance check).",
    )
    parser.add_argument(
        "--anomaly-method",
        choices=["iqr", "zscore"],
        default="iqr",
        help="Method used for anomaly detection (default: iqr).",
    )
    parser.add_argument(
        "--json",
        default=None,
        metavar="PATH",
        help="Export the report as JSON to the given path.",
    )
    parser.add_argument(
        "-v", "--verbose",
        action="store_true",
        help="Enable debug logging.",
    )
    return parser


def main(argv: list[str] | None = None) -> None:
    """Entry point for the CLI."""
    args = build_parser().parse_args(argv)
    logger = setup_logging(verbose=args.verbose)

    try:
        df = load_csv(args.input)
    except FileNotFoundError:
        print(f"Error: file not found – {args.input}", file=sys.stderr)
        sys.exit(1)
    except Exception as exc:
        logger.debug("Failed to load CSV", exc_info=True)
        print(f"Error: could not read CSV – {exc}", file=sys.stderr)
        sys.exit(1)

    result = analyze(df, target=args.target, anomaly_method=args.anomaly_method)

    print_report(result)

    if args.json:
        export_json(result, args.json)
        print(f"JSON report saved to {args.json}")
