"""CLI for textual-everforest."""

from __future__ import annotations

import argparse
from pathlib import Path

from textual_everforest.config import (
    CONFIG_FILENAME,
    default_config_path,
    load_theme_config,
    write_theme_config,
)


def _build_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(
        prog="textual-everforest",
        description="Configure Everforest Textual themes for a project.",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog=(
            "Examples:\n"
            "  textual-everforest --set-default dark\n"
            "  textual-everforest --set-default everforest-light-soft\n"
            "  textual-everforest --show\n"
            "  textual-everforest --path /path/to/project --set-default dark-soft\n"
        ),
    )
    parser.add_argument(
        "--path",
        type=Path,
        default=Path.cwd(),
        help="Project directory to write config into (default: cwd).",
    )
    parser.add_argument(
        "--set-default",
        metavar="THEME",
        help=(
            "Set default theme in config. Accepts dark, light, "
            "dark-hard, dark-medium, dark-soft, light-hard, light-medium, "
            "light-soft, or full theme name."
        ),
    )
    parser.add_argument(
        "--show",
        action="store_true",
        help="Show the current theme config if present.",
    )
    return parser


def main() -> int:
    parser = _build_parser()
    args = parser.parse_args()

    config_path = default_config_path(args.path)
    if args.set_default:
        config = write_theme_config(config_path, args.set_default)
        print(f"Wrote {CONFIG_FILENAME} with default theme {config.default_theme}")
        return 0

    if args.show:
        try:
            config = load_theme_config(config_path)
        except FileNotFoundError:
            print(f"No {CONFIG_FILENAME} found in {args.path}")
            return 1
        print(f"Default theme: {config.default_theme}")
        return 0

    parser.print_help()
    return 0


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