#!/usr/bin/env python3
"""
Push files from the working repo to both public Gitea repos.

Updates Seth/Mortdecai on git.sethpc.xyz and Mortdecai/Mortdecai on git.mortdec.ai
via API (different commit histories, can't git push directly).

Usage:
    python3 scripts/push_to_public_repos.py README.md branding/training_progress.svg MODEL_CARD.md
    python3 scripts/push_to_public_repos.py --all  # pushes README.md, MODEL_CARD.md, branding/*.svg
"""

import argparse
import base64
import json
import os
import sys
from pathlib import Path

import requests

PROJECT_ROOT = Path(__file__).resolve().parent.parent

REPOS = [
    {
        "name": "git.sethpc.xyz/Seth/Mortdecai",
        "base": "https://git.sethpc.xyz/api/v1/repos/Seth/Mortdecai/contents",
        "token": "REDACTED_GITEA_TOKEN",
    },
    {
        "name": "git.mortdec.ai/Mortdecai/Mortdecai",
        "base": "http://192.168.0.113:3000/api/v1/repos/Mortdecai/Mortdecai/contents",
        "token": "REDACTED_GITEA_TOKEN_2",
    },
]

DEFAULT_FILES = [
    "README.md",
    "MODEL_CARD.md",
    "branding/training_progress.svg",
]


def push_file(repo, remote_path, local_path, message):
    headers = {"Authorization": f"token {repo['token']}", "Content-Type": "application/json"}

    with open(local_path, "rb") as f:
        content_b64 = base64.b64encode(f.read()).decode()

    r = requests.get(f"{repo['base']}/{remote_path}", headers=headers)
    if r.ok:
        sha = r.json().get("sha", "")
        r2 = requests.put(f"{repo['base']}/{remote_path}", headers=headers, json={
            "message": message, "content": content_b64, "sha": sha,
        })
        return "updated" if r2.ok else f"failed: {r2.text[:100]}"
    else:
        r2 = requests.post(f"{repo['base']}/{remote_path}", headers=headers, json={
            "message": message, "content": content_b64,
        })
        return "created" if r2.ok else f"failed: {r2.text[:100]}"


def main():
    parser = argparse.ArgumentParser(description="Push files to public Gitea repos")
    parser.add_argument("files", nargs="*", help="Files to push (relative to project root)")
    parser.add_argument("--all", action="store_true", help="Push default files")
    parser.add_argument("--message", "-m", default="Update public repos", help="Commit message")
    args = parser.parse_args()

    files = args.files if args.files else (DEFAULT_FILES if args.all else [])
    if not files:
        print("No files specified. Use --all or list files.")
        sys.exit(1)

    for repo in REPOS:
        print(f"\n{repo['name']}:")
        for f in files:
            local = PROJECT_ROOT / f
            if not local.exists():
                print(f"  {f}: SKIPPED (not found)")
                continue
            status = push_file(repo, f, str(local), args.message)
            print(f"  {f}: {status}")


if __name__ == "__main__":
    main()
