name: Update README Badge

on:
  push:
    branches: ["**"]

jobs:
  update-badge:
    runs-on: ubuntu-latest
    permissions:
      contents: write

    steps:
      - name: Checkout repository
        uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Update README badges
        run: |
          python3 << 'EOF'
          import re
          import subprocess
          from datetime import datetime, timezone, timedelta

          # Ambil info dari git log
          author = subprocess.check_output(
              ["git", "log", "-1", "--format=%ae"],
              text=True
          ).strip()

          # Ambil actor dari env (GitHub username)
          import os
          actor = os.environ.get("GITHUB_ACTOR", "unknown")

          # Waktu commit terakhir dalam WIB (UTC+7)
          ts = subprocess.check_output(
              ["git", "log", "-1", "--format=%ct"],
              text=True
          ).strip()
          wib = datetime.fromtimestamp(int(ts), tz=timezone(timedelta(hours=7)))
          time_str = wib.strftime("%d/%m/%Y %H:%M WIB")

          # Format untuk shields.io badge
          badge_time = time_str.replace(" ", "_").replace("/", "%2F").replace(":", "%3A")
          badge_author = actor.replace("-", "--")
          profile_url = f"https://github.com/{actor}"

          # Badge markdown yang bersih
          new_time_badge = f"![Last Updated](https://img.shields.io/badge/Last_Updated-{badge_time}-blue?style=for-the-badge)"
          new_author_badge = f"![Author](https://img.shields.io/badge/By-{badge_author}-brightgreen?style=for-the-badge)"

          with open("README.md", "r", encoding="utf-8") as f:
              content = f.read()

          # Replace Last Updated badge
          content = re.sub(
              r'!\[Last Updated\]\(https://img\.shields\.io/badge/Last_Updated-[^)]+\)',
              new_time_badge,
              content
          )

          # Replace Author badge (dengan atau tanpa link)
          content = re.sub(
              r'\[!\[Author\]\(https://img\.shields\.io/badge/By-[^)]+\)\]\([^)]+\)',
              new_author_badge,
              content
          )
          # Fallback: tanpa link wrapper
          content = re.sub(
              r'!\[Author\]\(https://img\.shields\.io/badge/By-[^)]+\)',
              new_author_badge,
              content
          )

          with open("README.md", "w", encoding="utf-8") as f:
              f.write(content)

          print(f"Updated: {time_str} | Author: {actor}")
          EOF
        env:
          GITHUB_ACTOR: ${{ github.actor }}

      - name: Commit updated README
        run: |
          git config user.name "github-actions[bot]"
          git config user.email "github-actions[bot]@users.noreply.github.com"
          if git diff --quiet README.md; then
            echo "No changes, skipping."
          else
            git add README.md
            git commit -m "chore: update badge [skip ci]"
            git push
          fi