#!/usr/bin/env python3
"""Store the Kakao 상세보기 dashboard URL in macOS Keychain."""

from __future__ import annotations

import argparse
import subprocess
from urllib.parse import urlparse


KEYCHAIN_SERVICE = "codex-us-equity-kakao"
LOCAL_HOSTS = {"localhost", "127.0.0.1", "::1"}


def validate(url: str) -> None:
    parsed = urlparse(url)
    if parsed.scheme not in {"http", "https"} or not parsed.netloc:
        raise SystemExit("URL must start with http:// or https://")
    if parsed.hostname in LOCAL_HOSTS:
        raise SystemExit("Do not use localhost for Kakao 상세보기. Use a LAN, tunnel, or public URL.")


def main() -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument("url")
    args = parser.parse_args()
    validate(args.url)
    subprocess.run(
        [
            "security",
            "add-generic-password",
            "-U",
            "-s",
            KEYCHAIN_SERVICE,
            "-a",
            "KAKAO_DASHBOARD_URL",
            "-w",
            args.url,
        ],
        check=True,
    )
    print("KAKAO_DASHBOARD_URL saved.")
    return 0


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