#!/usr/bin/env python3
import json
import subprocess
import sys

# Get OAuth token from gog
result = subprocess.run(['gog', 'auth', 'tokens', 'jonny@jonnyshannon.com'], 
                       capture_output=True, text=True)
if result.returncode != 0:
    print(f"Error getting token: {result.stderr}")
    sys.exit(1)

# Parse token output
token_data = {}
for line in result.stdout.strip().split('\n'):
    if '\t' in line:
        key, value = line.split('\t', 1)
        token_data[key.strip()] = value.strip()

access_token = token_data.get('access_token')
if not access_token:
    print("Could not find access_token")
    sys.exit(1)

# Read AU companies data
with open('/Users/max/.openclaw/workspace/postharvest/au-companies.json', 'r') as f:
    au_data = json.load(f)

# Create new sheet
import requests

spreadsheet_id = '1uVd-xZFF4TEQGqtvw9z6W8fffeaifPCoLsek83GmEoQ'

# Add new sheet
add_sheet_request = {
    "requests": [{
        "addSheet": {
            "properties": {
                "title": "Australia",
                "gridProperties": {
                    "rowCount": 100,
                    "columnCount": 27,
                    "frozenRowCount": 1
                }
            }
        }
    }]
}

response = requests.post(
    f'https://sheets.googleapis.com/v4/spreadsheets/{spreadsheet_id}:batchUpdate',
    headers={
        'Authorization': f'Bearer {access_token}',
        'Content-Type': 'application/json'
    },
    json=add_sheet_request
)

if response.status_code != 200:
    print(f"Error creating sheet: {response.text}")
    sys.exit(1)

print(f"✅ Created Australia sheet")

# Add data to new sheet
update_request = {
    "range": "Australia!A1",
    "values": au_data
}

response = requests.put(
    f'https://sheets.googleapis.com/v4/spreadsheets/{spreadsheet_id}/values/Australia!A1',
    params={'valueInputOption': 'USER_ENTERED'},
    headers={
        'Authorization': f'Bearer {access_token}',
        'Content-Type': 'application/json'
    },
    json=update_request
)

if response.status_code != 200:
    print(f"Error adding data: {response.text}")
    sys.exit(1)

print(f"✅ Added {len(au_data)-1} Australian companies to the sheet")
print(f"https://docs.google.com/spreadsheets/d/{spreadsheet_id}/edit#gid=0")
