#!/usr/bin/env python3
"""Filter the source-traceable four-model eufy camera comparison CSV."""
from __future__ import annotations

import argparse
import csv
import json
from pathlib import Path
from typing import Iterable


DEFAULT_CSV = Path(__file__).resolve().with_name("eufy-camera-comparison.csv")


def load_rows(csv_path: Path) -> list[dict[str, str]]:
    with csv_path.open(newline="", encoding="utf-8") as handle:
        return list(csv.DictReader(handle))


def filter_rows(
    rows: Iterable[dict[str, str]],
    *,
    use_case: str | None = None,
    max_price: float | None = None,
    solar: bool = False,
    continuous: bool = False,
) -> list[dict[str, str]]:
    selected = []
    for row in rows:
        if use_case and row["recommendation"] != use_case:
            continue
        if max_price is not None and float(row["official_us_price_usd"]) > max_price:
            continue
        if solar and row["has_solar"].lower() != "true":
            continue
        if continuous and row["continuous_recording_supported"].lower() != "true":
            continue
        selected.append(row)
    return selected


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(
        description="Filter the eufy camera comparison by transparent constraints."
    )
    parser.add_argument("--csv", type=Path, default=DEFAULT_CSV, help="CSV input path")
    parser.add_argument(
        "--use-case",
        choices=[
            "small-area",
            "open-yard",
            "centralized-4k-system",
            "continuous-recording",
        ],
        help="Keep only the row assigned to this use case",
    )
    parser.add_argument(
        "--max-price",
        type=float,
        help="Keep rows at or below this official US price",
    )
    parser.add_argument("--solar", action="store_true", help="Keep solar models")
    parser.add_argument(
        "--continuous",
        action="store_true",
        help="Keep models marked as supporting continuous recording",
    )
    parser.add_argument(
        "--format",
        choices=["table", "json"],
        default="table",
        help="Output format",
    )
    return parser.parse_args()


def print_table(rows: list[dict[str, str]]) -> None:
    if not rows:
        print("No matching cameras.")
        return
    headers = [
        "model",
        "official_us_price_usd",
        "recording_mode",
        "official_product_url",
    ]
    print("\t".join(headers))
    for row in rows:
        print("\t".join(row[header] for header in headers))


def main() -> None:
    args = parse_args()
    rows = filter_rows(
        load_rows(args.csv),
        use_case=args.use_case,
        max_price=args.max_price,
        solar=args.solar,
        continuous=args.continuous,
    )
    if args.format == "json":
        print(json.dumps(rows, indent=2))
    else:
        print_table(rows)


if __name__ == "__main__":
    main()
