"""
create_app_key.py — create the app's MinIO user, limited to ONE bucket, without `mc` and without the web console.

Why: MinIO's free web console ("Community Edition", 2025+) only browses buckets: users, keys and policies are gone
from it, and the free `mc` binaries were withdrawn (dl.min.io answers 410). The official Python SDK still speaks the
admin API, so an administrator of the MinIO can do it from any PC with Python.

    python -m venv minio-venv
    minio-venv\\Scripts\\pip install minio==7.2.20          (Linux: minio-venv/bin/pip)
    minio-venv\\Scripts\\python create_app_key.py s3.storyface.ai photos-meeconic

Asks for the administrator's user and password (not echoed, not stored), then:
  1. creates/updates the policy `meeconic-app`: list + read + write + delete in THAT bucket only (the same as
     meeconic-app-policy.json, with the bucket name filled in);
  2. creates/updates the user `meeconic-app` with a new random secret and attaches the policy;
  3. prints the lines for backend/.env. Running it again gives the user a NEW secret (the old one stops working).
"""
import getpass
import json
import secrets
import sys
from pathlib import Path

from minio import Minio
from minio.credentials import StaticProvider
from minio.minioadmin import MinioAdmin

APP_USER = "meeconic-app"
POLICY = "meeconic-app"


def main() -> int:
    if len(sys.argv) not in (3, 4):
        print(__doc__)
        return 2
    endpoint, bucket = sys.argv[1].replace("https://", "").rstrip("/"), sys.argv[2]
    if len(sys.argv) == 4:                       # optional file: user on line 1, password on line 2
        with open(sys.argv[3], encoding="utf-8-sig") as f:
            admin_user, admin_pass = [line.rstrip("\r\n") for line in f.readlines()[:2]]
    else:
        admin_user = input("MinIO administrator user: ").strip()
        admin_pass = getpass.getpass("MinIO administrator password: ")

    # A plain S3 call first, with the same credentials: SignatureDoesNotMatch HERE means the password is wrong;
    # if this passes and the admin calls below fail, the admin API is the problem (proxy, not an admin).
    try:
        buckets = [b.name for b in Minio(endpoint, admin_user, admin_pass, secure=True).list_buckets()]
        print(f"0/3 credentials accepted by S3 (sees {len(buckets)} buckets; {bucket!r} "
              f"{'found' if bucket in buckets else 'NOT FOUND'})")
    except Exception as exc:
        print(f"\nFAILED before any change, plain S3 login refused: {exc}")
        print("With SignatureDoesNotMatch the user exists but the password is not this one.")
        return 1
    adm = MinioAdmin(endpoint=endpoint, credentials=StaticProvider(admin_user, admin_pass), secure=True)

    policy = {
        "Version": "2012-10-17",
        "Statement": [
            {"Effect": "Allow", "Action": ["s3:GetBucketLocation", "s3:ListBucket"],
             "Resource": [f"arn:aws:s3:::{bucket}"]},
            {"Effect": "Allow", "Action": ["s3:GetObject", "s3:PutObject", "s3:DeleteObject"],
             "Resource": [f"arn:aws:s3:::{bucket}/*"]},
        ],
    }
    try:
        adm.policy_add(POLICY, policy=policy)
        print(f"1/3 policy {POLICY!r}: only bucket {bucket!r}")
        secret = secrets.token_urlsafe(30)
        adm.user_add(APP_USER, secret)
        print(f"2/3 user {APP_USER!r} created")
        try:
            adm.attach_policy([POLICY], user=APP_USER)
        except Exception as exc:                       # already attached (second run): check instead of failing
            if POLICY not in adm.user_info(APP_USER):
                raise exc
        info = json.loads(adm.user_info(APP_USER))
        print(f"3/3 policy attached: {info.get('policyName')}")
    except Exception as exc:
        print(f"\nFAILED: {exc}")
        print("Is this user an ADMINISTRATOR of the MinIO (root or with admin rights)? The console login of a")
        print("normal user cannot create users.")
        return 1

    lines = {"S3_ENDPOINT_URL": f"https://{endpoint}", "S3_ACCESS_KEY": APP_USER,
             "S3_SECRET_KEY": secret, "S3_BUCKET": bucket}
    env = Path(__file__).resolve().parents[2] / "backend" / ".env"
    if len(sys.argv) == 4 and env.exists():
        # Run with a credentials file (unattended): the secret goes straight into backend/.env, never on screen.
        out, seen = [], set()
        for line in env.read_text(encoding="utf-8").splitlines():
            name = line.split("=", 1)[0].strip()
            if name in lines:
                line, _ = f"{name}={lines[name]}", seen.add(name)
            out.append(line)
        out += [f"{k}={v}" for k, v in lines.items() if k not in seen]
        env.write_text("\n".join(out) + "\n", encoding="utf-8")
        print(f"\nS3_* lines written into {env} (secret not shown).")
        return 0
    print("\nPut these lines in backend/.env (the secret is shown only now):\n")
    for k, v in lines.items():
        print(f"{k}={v}")
    return 0


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