"""Command-line interface for onsight_trend."""

import argparse
import sys
from pathlib import Path

import pandas as pd

from . import analyze_trend
from .config import DEFAULT_MAGNITUDE_CATEGORIES as _DEFAULT_CATS


def _parse_magnitude_categories(s: str) -> dict:
    """Parse magnitude_categories from string like 'low:0,25 medium:25,100 high:100,inf'."""
    if not s or s.strip() == "":
        return _DEFAULT_CATS.copy()
    result = {}
    for part in s.split():
        if ":" in part:
            name, range_str = part.split(":", 1)
            lo_str, hi_str = range_str.split(",")
            lo = float(lo_str.strip())
            hi = float("inf") if hi_str.strip().lower() in ("inf", "infinity") else float(hi_str.strip())
            result[name.strip()] = (lo, hi)
    return result if result else _DEFAULT_CATS.copy()


def main():
    parser = argparse.ArgumentParser(description="onsight_trend - Time-series trend analysis")
    parser.add_argument("csv_path", nargs="?", help="Path to CSV file (datetime + parameter columns)")
    parser.add_argument("--duration", "-d", type=float, default=7, help="Analysis duration in days")
    parser.add_argument(
        "--magnitude-categories",
        "-m",
        type=str,
        default=None,
        help="Custom categories: 'low:0,25 medium:25,100 high:100,inf'",
    )
    args = parser.parse_args()

    if not args.csv_path:
        print("Usage: onsight_trend <csv_path> [--duration 7] [--magnitude-categories '...']")
        sys.exit(1)

    path = Path(args.csv_path)
    if not path.exists():
        print(f"Error: File not found: {path}")
        sys.exit(1)

    df = pd.read_csv(path)
    mag_cats = _parse_magnitude_categories(args.magnitude_categories) if args.magnitude_categories else None

    try:
        result = analyze_trend(df, duration_days=args.duration, magnitude_categories=mag_cats)
    except (ValueError, TypeError) as e:
        print(f"Error: {e}")
        sys.exit(1)

    print(f"Direction: {result.direction}")
    print(f"Magnitude: {result.magnitude} ({result.magnitude_pct}%)")
    print(f"Confidence: {result.confidence}%")
    print(f"Category: {result.magnitude_category}")
