#!/usr/bin/env python3
"""Launch the native macOS Keychain helper without accepting secret arguments."""

from __future__ import annotations

import argparse
import os
import platform
import plistlib
import subprocess
import sys
import tempfile
from collections.abc import Iterator
from contextlib import contextmanager
from pathlib import Path


class SafeArgumentParser(argparse.ArgumentParser):
    def error(self, message: str) -> None:
        raise ValueError(message)


def parse_args() -> argparse.Namespace:
    parser = SafeArgumentParser(allow_abbrev=False)
    parser.add_argument("--service", required=True)
    parser.add_argument("--account", required=True)
    parser.add_argument("--label", default="Private credential")
    actions = parser.add_mutually_exclusive_group(required=True)
    actions.add_argument("--store", action="store_true")
    actions.add_argument("--status", action="store_true")
    actions.add_argument(
        "--delete-test-item", action="store_true", help=argparse.SUPPRESS
    )
    return parser.parse_args()


def validate_metadata(args: argparse.Namespace) -> bool:
    values = (args.service, args.account, args.label)
    return all(value and "\x00" not in value for value in values)


@contextmanager
def native_command() -> Iterator[tuple[list[str], Path | None] | None]:
    test_helper = os.environ.get("PRIVATE_PASSWORD_STORAGE_TEST_HELPER")
    if test_helper:
        yield ([test_helper], None)
        return
    if sys.platform != "darwin":
        yield None
        return

    discovery = subprocess.run(
        ["/usr/bin/xcrun", "--find", "swiftc"],
        check=False,
        capture_output=True,
        text=True,
    )
    if discovery.returncode != 0:
        yield None
        return
    if not discovery.stdout.strip():
        yield None
        return

    target = f"{platform.machine()}-apple-macosx12.0"
    with tempfile.TemporaryDirectory(prefix="private-password-storage-") as temp:
        app = Path(temp) / "Private Password Storage.app"
        macos = app / "Contents" / "MacOS"
        macos.mkdir(parents=True)
        executable = macos / "private-password-storage-native"
        info = {
            "CFBundleDisplayName": "Private Password Storage",
            "CFBundleExecutable": executable.name,
            "CFBundleIdentifier": "dev.codex.private-password-storage",
            "CFBundleName": "Private Password Storage",
            "CFBundlePackageType": "APPL",
            "CFBundleVersion": "1",
            "CFBundleShortVersionString": "1.0",
            "LSMinimumSystemVersion": "12.0",
            "NSHighResolutionCapable": True,
        }
        with (app / "Contents" / "Info.plist").open("wb") as handle:
            plistlib.dump(info, handle)

        compilation = subprocess.run(
            [
                "/usr/bin/xcrun",
                "swiftc",
                "-target",
                target,
                str(Path(__file__).with_suffix(".swift")),
                "-o",
                str(executable),
            ],
            check=False,
            capture_output=True,
            text=True,
        )
        if compilation.returncode != 0:
            yield None
            return
        yield ([str(executable)], app)


def action_args(args: argparse.Namespace) -> list[str]:
    if args.store:
        action = "--store"
    elif args.status:
        action = "--status"
    else:
        action = "--delete-test-item"
    return [
        "--service",
        args.service,
        "--account",
        args.account,
        "--label",
        args.label,
        action,
    ]


def main() -> int:
    try:
        args = parse_args()
    except (ValueError, SystemExit):
        sys.stdout.write("error\n")
        return 64

    if not validate_metadata(args):
        sys.stdout.write("error\n")
        return 64

    with native_command() as native:
        if native is None:
            sys.stdout.write("error\n")
            return 69
        command, app = native
        try:
            if args.store and app is not None:
                result_file = app.parent / "store-status"
                completed = subprocess.run(
                    [
                        "/usr/bin/open",
                        "-W",
                        "-n",
                        str(app),
                        "--args",
                        *action_args(args),
                        "--result-file",
                        str(result_file),
                    ],
                    check=False,
                    capture_output=True,
                    text=True,
                )
                output = (
                    result_file.read_text(encoding="utf-8").strip()
                    if result_file.is_file()
                    else ""
                )
            else:
                completed = subprocess.run(
                    [*command, *action_args(args)],
                    check=False,
                    capture_output=True,
                    text=True,
                )
                output = completed.stdout.strip()
        except KeyboardInterrupt:
            sys.stdout.write("cancelled\n")
            return 1

    allowed = {
        "stored": {"stored", "cancelled"},
        "status": {"present", "absent"},
        "delete": {"absent"},
    }
    expected = "stored" if args.store else "status" if args.status else "delete"
    if completed.returncode not in (0, 1) or output not in allowed[expected]:
        sys.stdout.write("error\n")
        return 1

    sys.stdout.write(f"{output}\n")
    if expected == "stored" and output != "stored":
        return 1
    return completed.returncode


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