#!/usr/bin/env python3
"""Write processed Content rows to the LL portal sheet's Content tab."""

import json, time, urllib.request, urllib.parse
from pathlib import Path

SHEET_ID = "1aCLZMcvLbacFHrZwuTBlgwezVHoAxFNYpmapqN9AVXY"
RANGE = "Content!A1"
SHEETS_BASE = "https://sheets.googleapis.com/v4/spreadsheets"
GOOGLE_TOKEN_PATH = Path.home() / ".config/google-workspace-mcp/profiles/emerson-north/tokens.json"
GOOGLE_CREDS_PATH = Path.home() / ".config/google-workspace-mcp/profiles/emerson-north/credentials.json"

def get_access_token():
    tokens = json.loads(GOOGLE_TOKEN_PATH.read_text())
    # Check if token is still valid
    if tokens.get("expiry"):
        expiry = tokens["expiry"]
        # Handle both float and ISO string formats
        if isinstance(expiry, str):
            from datetime import datetime
            try:
                exp_time = datetime.fromisoformat(expiry.replace("Z", "+00:00")).timestamp()
            except:
                exp_time = 0
        else:
            exp_time = float(expiry)
        if time.time() < exp_time - 60:
            return tokens["token"]

    # Refresh the token
    creds = json.loads(GOOGLE_CREDS_PATH.read_text())
    client_id = creds["installed"]["client_id"]
    client_secret = creds["installed"]["client_secret"]
    refresh_token = tokens["refresh_token"]

    data = urllib.parse.urlencode({
        "client_id": client_id,
        "client_secret": client_secret,
        "refresh_token": refresh_token,
        "grant_type": "refresh_token"
    }).encode()

    req = urllib.request.Request(
        "https://oauth2.googleapis.com/token",
        data=data,
        method="POST"
    )
    with urllib.request.urlopen(req) as r:
        result = json.loads(r.read())

    return result["access_token"]


def sheets_request(method, path, body=None):
    token = get_access_token()
    url = f"{SHEETS_BASE}/{path}"
    data = json.dumps(body).encode() if body else None
    req = urllib.request.Request(url, data=data, method=method)
    req.add_header("Authorization", f"Bearer {token}")
    req.add_header("Content-Type", "application/json")
    with urllib.request.urlopen(req) as r:
        return json.loads(r.read())


def main():
    # Load the prepared rows
    rows_data = json.loads(Path("/Users/bryce/FLSM/.tmp/content_rows.json").read_text())
    values = rows_data["values"]

    print(f"Writing {len(values)-1} data rows + header to Content tab...")

    # First clear the Content tab (except if already empty - just write from A1)
    encoded_range = urllib.parse.quote(RANGE)
    body = {
        "range": RANGE,
        "majorDimension": "ROWS",
        "values": values
    }

    result = sheets_request(
        "PUT",
        f"{SHEET_ID}/values/{encoded_range}?valueInputOption=RAW",
        body
    )

    updated = result.get("updatedCells", 0)
    updated_rows = result.get("updatedRows", 0)
    print(f"Success: {updated_rows} rows, {updated} cells written")
    print(f"Range: {result.get('updatedRange', '')}")


if __name__ == "__main__":
    main()
