from pathlib import Path
import datetime
import hashlib
import json
import os
import subprocess


p = Path.cwd().resolve()
assert (p / "project.json").exists()
assert p.name.startswith(("025-", "026-", "027-", "028-", "029-"))
key = os.environ["POSTIZ_API_KEY"]
url = "https://postiz-api.pain.io.vn/public/v1/upload"


def sha(path):
    digest = hashlib.sha256()
    with path.open("rb") as stream:
        for block in iter(lambda: stream.read(1024 * 1024), b""):
            digest.update(block)
    return digest.hexdigest()


def upload(path):
    result = subprocess.run(
        [
            "curl",
            "-sS",
            "-w",
            "\n%{http_code}",
            "-X",
            "POST",
            url,
            "-H",
            "Authorization: " + key,
            "-F",
            "file=@" + str(path),
        ],
        text=True,
        capture_output=True,
        check=True,
    )
    body, code = result.stdout.rsplit("\n", 1)
    assert code in ("200", "201"), (code, body)
    data = json.loads(body)
    assert data.get("id") and data.get("path")
    return {
        "id": data["id"],
        "path": data["path"],
        "local_path": str(path.resolve()),
        "size": path.stat().st_size,
        "sha256": sha(path),
        "uploaded_at": datetime.datetime.now(datetime.timezone.utc).isoformat(),
        "http_status": int(code),
    }


ledger = {
    "thumbnail": upload(p / "images/intro_poster.png"),
    "facebook_video": upload(p / "video/output/final-fb.mp4"),
    "youtube_video": upload(p / "video/output/final.mp4"),
}
(p / "logs/postiz_uploads_bgm_remediation.json").write_text(
    json.dumps(ledger, ensure_ascii=False, indent=2) + "\n"
)
print(json.dumps({k: {"id": v["id"], "http_status": v["http_status"]} for k, v in ledger.items()}))