import argparse
import os
import sys
from .hardener import validate_input_path, build_output_path, harden_config


def parse_args(argv):
    parser = argparse.ArgumentParser(
        description="Harden and obfuscate OpenVPN client configuration (.ovpn)."
    )
    parser.add_argument(
        "config",
        help="Path to the source .ovpn configuration file",
    )
    return parser.parse_args(argv)


def main(argv=None):
    if argv is None:
        argv = sys.argv[1:]
    try:
        args = parse_args(argv)
        input_path = os.path.abspath(args.config)
        validate_input_path(input_path)
        output_path = build_output_path(input_path)
        if os.path.abspath(output_path) == input_path:
            raise RuntimeError("Output path resolves to the same as input; aborting.")
        if os.path.exists(output_path):
            print(f"Warning: Output file already exists and will be overwritten: {output_path}", file=sys.stderr)
        harden_config(input_path, output_path)
        return 0
    except (FileNotFoundError, PermissionError, ValueError, OSError, RuntimeError) as e:
        print(f"Error: {e}", file=sys.stderr)
        return 1


if __name__ == "__main__":
    sys.exit(main())
