#!/usr/bin/env python3
"""Stub s5cmd for the archive script: `[--endpoint-url X] sync --size-only [--exclude PAT] SRC/ s3://B/K/` and
`ls s3://B/K/*`."""
import fnmatch
import os
import shutil
import sys
from pathlib import Path


def bucket(url: str) -> Path:
    return Path(os.environ["FLYLOFT_FAKE_S3"]) / url.removeprefix("s3://")


def ls(pattern: str) -> int:
    assert pattern.startswith("s3://") and pattern.endswith("/*"), pattern
    root = bucket(pattern.removesuffix("/*"))
    found = sorted(p for p in root.rglob("*") if p.is_file()) if root.is_dir() else []
    if not found:
        print(f'ERROR "ls {pattern}": no object found', file=sys.stderr)
        return 1
    for path in found:
        print(f"2026/10/26 12:00:00 {path.stat().st_size:>12} {path.relative_to(root)}")
    return 0


def sync(src: str, dst: str, exclude: str | None = None) -> int:
    assert dst.startswith("s3://"), dst
    dest = bucket(dst)
    drop = os.environ.get("FLYLOFT_FAKE_S3_DROP")
    skip_hidden = os.environ.get("FLYLOFT_FAKE_S3_SKIP_HIDDEN") == "1"
    source = Path(src)
    for path in sorted(p for p in source.rglob("*") if p.is_file()):
        rel = path.relative_to(source)
        if exclude and fnmatch.fnmatch(rel.as_posix(), exclude):
            continue
        if path.name == drop or (skip_hidden and any(part.startswith(".") for part in rel.parts)):
            continue
        target = dest / rel
        if target.exists() and target.stat().st_size == path.stat().st_size:
            continue
        target.parent.mkdir(parents=True, exist_ok=True)
        shutil.copyfile(path, target)
    return 0


def main(argv: list[str]) -> int:
    args = list(argv)
    if args[:1] == ["--endpoint-url"]:
        args = args[2:]
    match args:
        case ["sync", "--size-only", src, dst]:
            return sync(src, dst)
        case ["sync", "--size-only", "--exclude", exclude, src, dst]:
            return sync(src, dst, exclude)
        case ["ls", pattern]:
            return ls(pattern)
    raise AssertionError(argv)


sys.exit(main(sys.argv[1:]))
