name: Auto Backup - WBS-9.7

on:
  schedule:
    # 매일 자정 (UTC)
    - cron: '0 0 * * *'
  workflow_dispatch:

jobs:
  daily-backup:
    runs-on: ubuntu-latest
    name: Daily Backup

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

      - name: Setup Python
        run: |
          python --version

      - name: Run Daily Backup
        run: |
          python tools/backup_recovery_manager_v1.py

      - name: Cleanup Old Backups
        run: |
          python -c "
          from tools.backup_recovery_manager_v1 import BackupRecoveryManager
          manager = BackupRecoveryManager(retention_days=30)
          result = manager.cleanup_old_backups()
          print(f'Cleanup: {result}')
          "

      - name: Log Backup Result
        if: always()
        run: |
          echo "Backup completed at $(date)"
          ls -lh backups/ | tail -5

  weekly-full-backup:
    runs-on: ubuntu-latest
    name: Weekly Full Backup

    # 매주 월요일 1:00 UTC
    schedule:
      - cron: '0 1 * * 1'

    steps:
      - name: Checkout
        uses: actions/checkout@v3

      - name: Setup Python
        run: python --version

      - name: Create Weekly Full Backup
        run: |
          python -c "
          from tools.backup_recovery_manager_v1 import BackupRecoveryManager
          from pathlib import Path

          manager = BackupRecoveryManager()
          result = manager.create_weekly_full_backup()
          print(f'Weekly backup: {result}')

          # 신뢰성 테스트
          if 'backup_name' in result:
              integrity = manager.test_backup_integrity(result['backup_name'])
              print(f'Integrity: {integrity}')
          "

      - name: Backup to Cloud (Optional)
        continue-on-error: true
        run: |
          # 원격 백업 서버로 동기화 (설정 필요)
          # rsync -av backups/ admin@BACKUP_SERVER_IP:/backup/data_feed/
          echo "Cloud sync would run here if configured"

      - name: Notify Completion
        if: success()
        run: |
          echo "Weekly backup completed successfully"
          df -h | grep -E "Filesystem|data"

  backup-health-check:
    runs-on: ubuntu-latest
    name: Backup Health Check

    # 매일 12:00 UTC
    schedule:
      - cron: '0 12 * * *'

    steps:
      - name: Checkout
        uses: actions/checkout@v3

      - name: Check Backup Integrity
        run: |
          python -c "
          from tools.backup_recovery_manager_v1 import BackupRecoveryManager
          from pathlib import Path

          manager = BackupRecoveryManager()

          # 가장 최근 백업 확인
          backups = sorted(Path('backups/').glob('*'), key=lambda p: p.stat().st_mtime, reverse=True)

          if backups:
              latest = backups[0].name
              print(f'Latest backup: {latest}')

              integrity = manager.test_backup_integrity(latest)
              print(f'Status: {integrity.get(\"status\")}')

              if integrity.get('database_integrity') != 'ok':
                  print('WARNING: Database integrity issue detected')
          else:
              print('ERROR: No backups found')
          "

      - name: Log Backup Statistics
        run: |
          echo "=== Backup Statistics ==="
          find backups/ -type f -name "metadata.json" | wc -l
          du -sh backups/ | awk '{print "Total size: " $1}'

  test-recovery:
    runs-on: ubuntu-latest
    name: Monthly Recovery Test

    # 매월 1일 2:00 UTC
    schedule:
      - cron: '0 2 1 * *'

    steps:
      - name: Checkout
        uses: actions/checkout@v3

      - name: Test Recovery Procedure
        run: |
          python -c "
          from tools.backup_recovery_manager_v1 import BackupRecoveryManager
          from pathlib import Path
          import tempfile

          manager = BackupRecoveryManager()

          # 가장 최근 백업에서 복구 테스트
          backups = sorted(Path('backups/').glob('*'), key=lambda p: p.stat().st_mtime, reverse=True)

          if backups:
              test_backup = backups[0].name

              # 임시 디렉토리에 복구
              with tempfile.TemporaryDirectory() as tmpdir:
                  result = manager.restore_from_backup(test_backup, tmpdir)
                  print(f'Recovery test: {result.get(\"status\")}')
                  print(f'Recovery time: {result.get(\"recovery_time_seconds\")}s')

                  if result.get('status') == 'SUCCESS':
                      print('Recovery procedure validated')
                  else:
                      print('ERROR: Recovery test failed')
          "

      - name: Document Recovery Capability
        run: |
          echo "Monthly recovery test completed"
          echo "Recovery time target: < 1 hour"
          echo "Success rate target: 99%"
