"""CLI 진입점."""

from __future__ import annotations

import argparse
import json
import sys
from pathlib import Path

_DATA = Path(__file__).resolve().parent.parent / "data" / "todos.json"


def _load() -> list[str]:
    if not _DATA.exists():
        return []
    raw = _DATA.read_text(encoding="utf-8").strip()
    if not raw:
        return []
    return json.loads(raw)


def _save(items: list[str]) -> None:
    _DATA.parent.mkdir(parents=True, exist_ok=True)
    _DATA.write_text(json.dumps(items, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")


def main(argv: list[str] | None = None) -> int:
    parser = argparse.ArgumentParser(
        prog="todo_cli",
        description="Minimal todo list CLI for Claude Code workbook.",
    )
    sub = parser.add_subparsers(dest="cmd", required=True)

    sub.add_parser("list", help="Show all todos")

    p_add = sub.add_parser("add", help="Add a todo")
    p_add.add_argument("text", help="Todo text")

    args = parser.parse_args(argv)

    if args.cmd == "list":
        for i, item in enumerate(_load(), start=1):
            print(f"{i}. {item}")
        return 0

    if args.cmd == "add":
        text = (args.text or "").strip()
        if not text:
            print("empty item rejected", file=sys.stderr)
            return 1
        items = _load()
        items.append(text)
        _save(items)
        return 0

    return 1


if __name__ == "__main__":
    raise SystemExit(main())
