import os
import requests
import json
from dotenv import load_dotenv

load_dotenv(dotenv_path="/home/node/clawd/.env")

NOTION_TOKEN = os.getenv("NOTION_API_KEY")
HEADERS = {
    "Authorization": f"Bearer {NOTION_TOKEN}",
    "Content-Type": "application/json",
    "Notion-Version": "2022-06-28"
}

PROJECT_ID = "2ea88f42-8544-8074-9ad8-c24d283bc1c9"

def find_tasks_db():
    url = "https://api.notion.com/v1/search"
    payload = {"query": "Tasks", "filter": {"value": "database", "property": "object"}}
    resp = requests.post(url, headers=HEADERS, json=payload)
    if resp.status_code == 200:
        results = resp.json().get("results", [])
        if results:
            return results[0]['id']
    return None

def get_project_tasks(db_id):
    url = f"https://api.notion.com/v1/databases/{db_id}/query"
    # We look for tasks linked to the project ID via a relation property (usually "Project")
    payload = {
        "filter": {
            "property": "Project",
            "relation": {
                "contains": PROJECT_ID
            }
        }
    }
    resp = requests.post(url, headers=HEADERS, json=payload)
    if resp.status_code != 200:
        print(f"Error querying tasks: {resp.text}")
        return []
        
    return resp.json().get("results", [])

def print_tasks():
    db_id = find_tasks_db()
    if not db_id:
        print("❌ Tasks DB not found.")
        return

    print(f"--- Tasks for Project {PROJECT_ID} ---")
    tasks = get_project_tasks(db_id)
    
    for task in tasks:
        props = task['properties']
        name = "Unknown"
        if "Name" in props and props["Name"]["title"]:
            name = props["Name"]["title"][0]["plain_text"]
        elif "Task" in props and props["Task"]["title"]:
            name = props["Task"]["title"][0]["plain_text"]
            
        status = "Unknown"
        if "Status" in props and props["Status"]["status"]:
            status = props["Status"]["status"]["name"]
            
        print(f"- [{status}] {name} ({task['id']})")

if __name__ == "__main__":
    print_tasks()
