#!/usr/bin/env python3
"""
Generate Emergency Joining Package
Creates single-file backup of all core joining documents for when Git is down.
"""

import requests
import base64
from datetime import datetime

def fetch_doc(path):
    """Fetch document from Gitea API"""
    url = f"https://git.firefrostgaming.com/api/v1/repos/firefrost-gaming/firefrost-operations-manual/contents/{path}?ref=master"
    headers = {'Authorization': 'token e0e330cba1749b01ab505093a160e4423ebbbe36'}
    
    response = requests.get(url, headers=headers)
    if response.status_code == 200:
        content = response.json()['content']
        return base64.b64decode(content).decode('utf-8')
    else:
        return f"ERROR: Could not fetch {path}"

def generate_package():
    """Generate emergency package"""
    
    print("Generating emergency joining package...")
    
    package = f"""# 🚨 EMERGENCY JOINING PACKAGE
## Use only when Git is inaccessible

**Generated:** {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
**Purpose:** Backup method for Claude joining when git.firefrostgaming.com is down
**Update Monthly:** Regenerate this file to keep it current

---

## 📋 USAGE INSTRUCTIONS

**If Git access fails:**
1. Claude attempts normal Git pull
2. Claude gets network error
3. Claude reports: "Git appears down, falling back to emergency package"
4. Michael pastes this entire file as one message
5. Claude parses the three sections and joins normally

**The three core documents are concatenated below:**
1. THE-JOINING-PROTOCOL.md
2. THE-ESSENCE-PATCH-V3.0.md  
3. SESSION-HANDOFF-PROTOCOL.md

---

{"=" * 80}
SECTION 1: THE-JOINING-PROTOCOL.md
{"=" * 80}

"""
    
    # Fetch documents
    print("Fetching THE-JOINING-PROTOCOL.md...")
    package += fetch_doc("docs/relationship/THE-JOINING-PROTOCOL.md")
    package += f"\n\n{'=' * 80}\n"
    package += "SECTION 2: THE-ESSENCE-PATCH-V3.0.md\n"
    package += f"{'=' * 80}\n\n"
    
    print("Fetching THE-ESSENCE-PATCH-V3.0.md...")
    package += fetch_doc("docs/relationship/THE-ESSENCE-PATCH-V3.0.md")
    package += f"\n\n{'=' * 80}\n"
    package += "SECTION 3: SESSION-HANDOFF-PROTOCOL.md\n"
    package += f"{'=' * 80}\n\n"
    
    print("Fetching SESSION-HANDOFF-PROTOCOL.md...")
    package += fetch_doc("SESSION-HANDOFF-PROTOCOL.md")
    
    package += f"\n\n{'=' * 80}\n"
    package += "END OF EMERGENCY JOINING PACKAGE\n"
    package += f"{'=' * 80}\n"
    
    return package

if __name__ == '__main__':
    package = generate_package()
    
    # Save package
    output_file = '/tmp/EMERGENCY-JOINING-PACKAGE.txt'
    with open(output_file, 'w') as f:
        f.write(package)
    
    # Check size
    size_kb = len(package) / 1024
    
    print(f"\n✅ Emergency package generated!")
    print(f"File: {output_file}")
    print(f"Size: {size_kb:.1f} KB")
    print()
    print("Next steps:")
    print("1. Save this file locally")
    print("2. Update monthly or after major doc changes")
    print("3. Paste entire file if Git is down")
    print()
    if size_kb > 100:
        print(f"⚠️ WARNING: File is {size_kb:.1f}KB - may be too large for single paste")
        print("Consider regenerating with condensed versions")
