from __future__ import annotations

import argparse
import sys
from pathlib import Path
from typing import Sequence

from govoplan_core.core.install_config import env_template, validate_runtime_configuration


def parse_args(argv: Sequence[str] | None = None) -> argparse.Namespace:
    parser = argparse.ArgumentParser(description="Generate and validate GovOPlaN install/runtime configuration.")
    subparsers = parser.add_subparsers(dest="command", required=True)

    env_parser = subparsers.add_parser("env-template", help="Print or write an install .env template.")
    env_parser.add_argument("--profile", default="self-hosted", choices=("self-hosted", "production-like"), help="Template profile to generate.")
    env_parser.add_argument("--output", type=Path, help="Write the template to this path instead of stdout.")
    env_parser.add_argument("--overwrite", action="store_true", help="Overwrite an existing output path.")
    env_parser.add_argument("--generate-secrets", action="store_true", help="Generate a fresh MASTER_KEY_B64 in the template.")

    validate_parser = subparsers.add_parser("validate", help="Validate the current process environment.")
    validate_parser.add_argument("--profile", help="Install profile. Defaults to GOVOPLAN_INSTALL_PROFILE or APP_ENV.")
    validate_parser.add_argument("--strict", action="store_true", help="Treat warnings as errors.")
    validate_parser.add_argument("--format", choices=("text", "json"), default="text", help="Output format.")

    return parser.parse_args(argv)


def main(argv: Sequence[str] | None = None) -> int:
    args = parse_args(argv)
    if args.command == "env-template":
        payload = env_template(profile=args.profile, generate_secrets=args.generate_secrets)
        if args.output is None:
            print(payload, end="")
            return 0
        output = args.output.expanduser()
        if output.exists() and not args.overwrite:
            print(f"Refusing to overwrite existing file: {output}", file=sys.stderr)
            return 2
        output.parent.mkdir(parents=True, exist_ok=True)
        output.write_text(payload, encoding="utf-8")
        print(f"Wrote {output}")
        return 0

    if args.command == "validate":
        result = validate_runtime_configuration(profile=args.profile, strict=args.strict)
        print(result.to_json() if args.format == "json" else result.to_text())
        return 0 if result.ok else 1

    raise AssertionError(f"Unhandled command: {args.command}")


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