#!/usr/bin/env python3
"""Quick check of SharePoint Quality Systems Department file count."""

import requests
import subprocess
import json

# Get credentials from vault
def get_vault(path, field):
    result = subprocess.run(
        ["bash", ".claude/scripts/vault.sh", "get-field", path, field],
        capture_output=True, text=True, check=True
    )
    return result.stdout.strip()

# Birth Biologic credentials
tenant_id = "19a568e8-9e88-413b-9341-cbc224b39145"
client_id = "709e6eed-0711-4875-9c44-2d3518c47063"
client_secret = get_vault("msp-tools/computerguru-tenant-admin", "credentials.client_secret")
drive_id = "b!F8BzMb1YakCIWCyWlmczb09LHqtxDxVMpLT6kAwYmsM7NUY4oPLSRq7ng3tJq-E9"

# Get Graph token
token_data = {
    "client_id": client_id,
    "client_secret": client_secret,
    "scope": "https://graph.microsoft.com/.default",
    "grant_type": "client_credentials"
}
token_resp = requests.post(
    f"https://login.microsoftonline.com/{tenant_id}/oauth2/v2.0/token",
    data=token_data
)
token_resp.raise_for_status()
graph_token = token_resp.json()["access_token"]

headers = {"Authorization": f"Bearer {graph_token}"}

# Count all files recursively in SharePoint
def count_files_recursive(item_id=None):
    if item_id:
        url = f"https://graph.microsoft.com/v1.0/drives/{drive_id}/items/{item_id}/children"
    else:
        url = f"https://graph.microsoft.com/v1.0/drives/{drive_id}/root/children"

    count = 0
    while url:
        resp = requests.get(url, headers=headers)
        resp.raise_for_status()
        data = resp.json()

        for item in data.get("value", []):
            if "folder" in item:
                count += count_files_recursive(item["id"])
            else:
                count += 1

        url = data.get("@odata.nextLink")

    return count

print("Checking SharePoint Quality Systems Department RIGHT NOW...")
print()
print("Counting files in SharePoint...")
sharepoint_count = count_files_recursive()

print()
print(f"SharePoint: {sharepoint_count} files")
print(f"Datto: 3768 files")
print(f"Gap: {3768 - sharepoint_count} files")
print()

if sharepoint_count == 3768:
    print("[OK] MATCH - SharePoint has exactly 3768 files")
elif sharepoint_count < 3768:
    print(f"SYNCING - OneDrive still uploading {3768 - sharepoint_count} files")
else:
    print(f"[WARNING] SharePoint has MORE files than Datto ({sharepoint_count - 3768} extra)")
