from __future__ import annotations

import argparse
import logging
import sys

from src.config.config_file import apply_config_file
from src.commands import (
    config_cmd,
    enrich_cmd,
    exif_cmd,
    export_cmd,
    gbp_cmd,
    ingest_cmd,
    match_cmd,
    naming_cmd,
    organize_cmd,
    pipedrive_cmd,
    report_cmd,
    run_cmd,
)
from src.errors import UserError
from src.logging_setup import configure_logging, log_event

logger = logging.getLogger(__name__)


def main(argv: list[str] | None = None) -> int:
    parser = _build_parser()
    args = parser.parse_args(argv)

    try:
        apply_config_file(cli_value=getattr(args, "config", None), override_env=False)
        json_logging_enabled = configure_logging(
            cli_log_json=getattr(args, "log_json", None),
        )
        handler = getattr(args, "_handler", None)
        if handler is None:
            raise UserError("No handler registered for command.")
        if json_logging_enabled:
            log_event(logger, "cli.start", command=getattr(args, "cmd", None))
        code = int(handler(args))
        if json_logging_enabled:
            log_event(logger, "cli.complete", command=getattr(args, "cmd", None), exit_code=code)
        return code
    except UserError as exc:
        log_event(logger, "cli.user_error", level="error", message=str(exc))
        print(f"ERROR: {exc}", file=sys.stderr)
        return 2


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


def _build_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(prog="eventfoto-pipeline")
    parser.add_argument(
        "--config", help="Optional config file path (.env or .json). Env wins over file."
    )
    parser.add_argument(
        "--log-json",
        action="store_true",
        default=None,
        help="Enable JSON structured logging (stderr).",
    )
    sub = parser.add_subparsers(dest="cmd", required=True)
    for mod in (
        ingest_cmd,
        exif_cmd,
        pipedrive_cmd,
        match_cmd,
        enrich_cmd,
        naming_cmd,
        organize_cmd,
        export_cmd,
        gbp_cmd,
        run_cmd,
        report_cmd,
        config_cmd,
    ):
        mod.register(sub)
    return parser
