"""
check_storage.py — try every S3 call the app makes against the REAL bucket of backend/.env, before going live.

Why: the test suite runs on moto (an in-process imitation of S3). A real MinIO behind nginx can differ where
moto cannot tell: nginx refusing big uploads (`client_max_body_size`, multipart parts are 8 MB), metadata dropped
by a copy (the RGPD arrival time lives in `x-amz-meta-mtime`), a key that sees too much or a bucket left public.

    venv\\Scripts\\python scripts/check_storage.py        (or venv/bin/python on the server)

Only touches objects under `_check/` in the bucket and deletes them at the end. Does not need MySQL.
Exit code 0 = every check passed.
"""
import os
import sys
import time
import urllib.error
import urllib.request
import uuid
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
os.chdir(Path(__file__).resolve().parents[1])               # .env and relative paths, as when the app runs

from core import config  # noqa: E402

failures = 0


def step(name, fn):
    global failures
    t = time.time()
    try:
        note = fn()
        print(f"  OK    {name}" + (f"  ({note})" if note else "") + f"  [{time.time() - t:.1f}s]")
    except Exception as exc:
        failures += 1
        print(f"  FAIL  {name}: {exc}")


def main() -> int:
    if not (config.S3_ENDPOINT_URL and config.S3_ACCESS_KEY and config.S3_SECRET_KEY):
        print("S3_ENDPOINT_URL / S3_ACCESS_KEY / S3_SECRET_KEY are not set in backend/.env")
        return 2
    import boto3
    from botocore.config import Config
    # Same client settings as core/storage.py S3Storage.client.
    s3 = boto3.client("s3", endpoint_url=config.S3_ENDPOINT_URL, region_name=config.S3_REGION,
                      aws_access_key_id=config.S3_ACCESS_KEY, aws_secret_access_key=config.S3_SECRET_KEY,
                      config=Config(s3={"addressing_style": "path"}, signature_version="s3v4",
                                    retries={"max_attempts": 2, "mode": "standard"},
                                    connect_timeout=5, read_timeout=60))
    b = config.S3_BUCKET
    run = f"_check/{uuid.uuid4().hex[:8]}"
    small, big, moved = f"{run}/small.jpg", f"{run}/big.jpg", f"{run}/moved/small.jpg"
    mtime = 1700000000.5
    tmp = Path(config.STORAGE_CACHE_DIR) / "_check_big.bin"
    print(f"Bucket {b!r} at {config.S3_ENDPOINT_URL}")

    step("bucket answers (head_bucket)", lambda: s3.head_bucket(Bucket=b) and None)

    def put_small():
        s3.put_object(Bucket=b, Key=small, Body=b"x" * 1000, Metadata={"mtime": repr(mtime)})
    step("small upload", put_small)

    def put_big():
        # 20 MB: upload_file goes multipart above 8 MB, as for a real photo. nginx' default body limit (1 MB)
        # fails here with 413 Request Entity Too Large.
        tmp.parent.mkdir(parents=True, exist_ok=True)
        tmp.write_bytes(os.urandom(20 * 1024 * 1024))
        s3.upload_file(str(tmp), b, big, ExtraArgs={"Metadata": {"mtime": repr(mtime)}})
        size = s3.head_object(Bucket=b, Key=big)["ContentLength"]
        if size != tmp.stat().st_size:
            raise RuntimeError(f"{size} bytes stored, {tmp.stat().st_size} sent")
        return "20 MB, multipart"
    step("big upload (nginx body limit)", put_big)

    def meta_kept():
        got = s3.head_object(Bucket=b, Key=small).get("Metadata", {}).get("mtime")
        if got is None or float(got) != mtime:
            raise RuntimeError(f"x-amz-meta-mtime = {got!r}, expected {mtime!r}")
    step("arrival time kept in metadata", meta_kept)

    def copy_keeps_meta():
        s3.copy_object(Bucket=b, Key=moved, MetadataDirective="COPY", CopySource={"Bucket": b, "Key": small})
        got = s3.head_object(Bucket=b, Key=moved).get("Metadata", {}).get("mtime")
        if got is None or float(got) != mtime:
            raise RuntimeError(f"after copy x-amz-meta-mtime = {got!r}")
    step("move (copy keeps the arrival time)", copy_keeps_meta)

    def replace_meta():
        s3.copy_object(Bucket=b, Key=moved, CopySource={"Bucket": b, "Key": moved},
                       MetadataDirective="REPLACE", Metadata={"mtime": "1600000000.0"})
        got = s3.head_object(Bucket=b, Key=moved)["Metadata"].get("mtime")
        if float(got) != 1600000000.0:
            raise RuntimeError(f"mtime = {got!r}")
    step("touch (metadata replaced in place)", replace_meta)

    def listing():
        keys = {o["Key"] for o in s3.list_objects_v2(Bucket=b, Prefix=run + "/").get("Contents", [])}
        if keys != {small, big, moved}:
            raise RuntimeError(f"listed {sorted(keys)}")
    step("listing (reconcile)", listing)

    def ranged_read():
        body = s3.get_object(Bucket=b, Key=big)["Body"]
        n = 0
        while chunk := body.read(1024 * 1024):
            n += len(chunk)
        if n != 20 * 1024 * 1024:
            raise RuntimeError(f"read {n} bytes")
    step("streamed read (paid download)", ranged_read)

    def not_public():
        url = f"{config.S3_ENDPOINT_URL.rstrip('/')}/{b}/{small}"
        try:
            urllib.request.urlopen(url, timeout=10)
        except urllib.error.HTTPError as e:
            if e.code in (401, 403):
                return f"anonymous GET -> {e.code}"
            raise RuntimeError(f"anonymous GET -> {e.code}")
        raise RuntimeError("anonymous GET returned the photo: the bucket is PUBLIC, set it private")
    step("bucket is private", not_public)

    def scoped_key():
        try:
            names = [x["Name"] for x in s3.list_buckets().get("Buckets", [])]
        except Exception:
            return "the key cannot list buckets (good)"
        others = [n for n in names if n != b]
        if others:
            raise RuntimeError(f"the app's key can see other buckets {others}: use the meeconic-app policy")
        return "sees only its bucket"
    step("key limited to its bucket", scoped_key)

    def cleanup():
        for k in (small, big, moved):
            s3.delete_object(Bucket=b, Key=k)
        left = s3.list_objects_v2(Bucket=b, Prefix=run + "/").get("KeyCount", 0)
        if left:
            raise RuntimeError(f"{left} objects left under {run}/")
    step("delete", cleanup)
    tmp.unlink(missing_ok=True)

    print("ALL CHECKS PASSED" if not failures else f"{failures} CHECK(S) FAILED")
    return 0 if not failures else 1


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