"""
Operation 3: Delete blank/empty contacts from Temp (15 contacts)
"""
import json
import subprocess
import time
import urllib.parse

TENANT_ID = "dd4a82e8-85a3-44ac-8800-07945ab4d95f"
CLIENT_ID = "fabb3421-8b34-484b-bc17-e46de9703418"
CLIENT_SECRET = "~QJ8Q~NyQSs4OcGqHZyPrA2CVnq9KBfKiimntbMO"
SCOPE = "https://graph.microsoft.com/.default"
USER = "barbara@bardach.net"
DATA_FILE = "D:/ClaudeTools/temp/bardach_temp_vs_main.json"
OUTPUT_FILE = "D:/ClaudeTools/temp/bardach_op3_delete_blank.json"

def get_token():
    url = f"https://login.microsoftonline.com/{TENANT_ID}/oauth2/v2.0/token"
    data = (
        f"client_id={CLIENT_ID}"
        f"&scope={urllib.parse.quote(SCOPE)}"
        f"&client_secret={urllib.parse.quote(CLIENT_SECRET)}"
        f"&grant_type=client_credentials"
    )
    result = subprocess.run(
        ["curl", "-s", "-X", "POST", url,
         "-H", "Content-Type: application/x-www-form-urlencoded",
         "-d", data],
        capture_output=True, text=True
    )
    resp = json.loads(result.stdout)
    if "access_token" not in resp:
        print(f"[ERROR] Token acquisition failed: {resp}")
        raise Exception("Failed to get token")
    print("[OK] Token acquired")
    return resp["access_token"]

def delete_contact(token, contact_id):
    url = f"https://graph.microsoft.com/v1.0/users/{USER}/contacts/{contact_id}"
    result = subprocess.run(
        ["curl", "-s", "-o", "/dev/null", "-w", "%{http_code}",
         "-X", "DELETE", url,
         "-H", f"Authorization: Bearer {token}"],
        capture_output=True, text=True
    )
    return result.stdout.strip()

def main():
    print("=" * 60)
    print("OPERATION 3: Delete blank contacts from Temp (15 contacts)")
    print("=" * 60)

    with open(DATA_FILE, "r") as f:
        data = json.load(f)

    blanks = data["blank"]
    total = len(blanks)
    print(f"[INFO] Loaded {total} blank contacts to delete")

    token = get_token()
    successes = []
    failures = []

    for i, contact in enumerate(blanks):
        temp_id = contact["temp_id"]
        status_code = delete_contact(token, temp_id)

        if status_code in ("204", "200"):
            successes.append({"temp_id": temp_id})
            print(f"  [{i+1}/{total}] DELETED blank contact {temp_id[:40]}... -> {status_code}")
        else:
            failures.append({"temp_id": temp_id, "status": status_code})
            print(f"  [{i+1}/{total}] FAILED  blank contact {temp_id[:40]}... -> {status_code}")

    results = {
        "operation": "delete_blank_contacts",
        "total": total,
        "successes": len(successes),
        "failures": len(failures),
        "failed_contacts": failures
    }

    with open(OUTPUT_FILE, "w") as f:
        json.dump(results, f, indent=2)

    print(f"\n[SUCCESS] Operation 3 complete")
    print(f"  Deleted: {len(successes)}/{total}")
    print(f"  Failed:  {len(failures)}/{total}")
    print(f"  Results: {OUTPUT_FILE}")

if __name__ == "__main__":
    main()
