import os
import json
import requests
from dotenv import load_dotenv

load_dotenv()

SESSION_FILE = ".dev_session/SESSION_INFO"

def debug_notion():
    if not os.path.exists(SESSION_FILE):
        print("No session file found.")
        return

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

    task_id = data.get("task_id")
    token = data.get("token")

    print(f"Debug Info:")
    print(f"Task ID: {task_id}")
    print(f"Token (first 4 chars): {token[:4]}...")

    url = f"https://api.notion.com/v1/pages/{task_id}"
    headers = {
        "Authorization": f"Bearer {token}",
        "Notion-Version": "2022-06-28",
        "Content-Type": "application/json"
    }

    # 1. Fetch Page
    print("\n--- Fetching Page Properties ---")
    resp = requests.get(url, headers=headers)
    if resp.status_code != 200:
        print(f"Error fetching page: {resp.status_code}")
        print(resp.text)
        return

    page_data = resp.json()
    properties = page_data.get("properties", {})
    
    print(f"Found {len(properties)} properties:")
    target_prop_name = "Total Duration (h)"
    found_target = False

    for name, prop in properties.items():
        type_ = prop.get("type")
        val = prop.get(type_)
        print(f"- '{name}' ({type_}): {val}")
        if name == target_prop_name:
            found_target = True

    if not found_target:
        print(f"\nCRITICAL: Property '{target_prop_name}' NOT found on this task!")
        # Check for similar names
        for name in properties.keys():
            if "duration" in name.lower() or "zeit" in name.lower() or "hours" in name.lower():
                print(f"  -> Did you mean: '{name}'?")
        return

    # 2. Try Update
    print(f"\n--- Attempting Update of '{target_prop_name}' ---")
    current_val = properties[target_prop_name].get("number") or 0.0
    print(f"Current Value: {current_val}")
    
    new_val = current_val + 0.01
    print(f"Updating to: {new_val}")

    update_payload = {
        "properties": {
            target_prop_name: {"number": new_val}
        }
    }
    
    patch_resp = requests.patch(url, headers=headers, json=update_payload)
    if patch_resp.status_code == 200:
        print("✅ Update Successful!")
        print(f"New Value on Server: {patch_resp.json()['properties'][target_prop_name].get('number')}")
    else:
        print(f"❌ Update Failed: {patch_resp.status_code}")
        print(patch_resp.text)

if __name__ == "__main__":
    debug_notion()
