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 read_memory():
    try:
        with open("memory/2026-02-17.md", "r") as f:
            return f.readlines()
    except FileNotFoundError:
        return []

def parse_markdown_to_blocks(lines):
    blocks = []
    for line in lines:
        line = line.strip()
        if not line:
            continue
            
        if line.startswith("# "):
            blocks.append({
                "object": "block",
                "type": "heading_1",
                "heading_1": {"rich_text": [{"type": "text", "text": {"content": line[2:]}}]}
            })
        elif line.startswith("## "):
            blocks.append({
                "object": "block",
                "type": "heading_2",
                "heading_2": {"rich_text": [{"type": "text", "text": {"content": line[3:]}}]}
            })
        elif line.startswith("### "):
            blocks.append({
                "object": "block",
                "type": "heading_3",
                "heading_3": {"rich_text": [{"type": "text", "text": {"content": line[4:]}}]}
            })
        elif line.startswith("- "):
            blocks.append({
                "object": "block",
                "type": "bulleted_list_item",
                "bulleted_list_item": {"rich_text": [{"type": "text", "text": {"content": line[2:]}}]}
            })
        else:
            blocks.append({
                "object": "block",
                "type": "paragraph",
                "paragraph": {"rich_text": [{"type": "text", "text": {"content": line}}]}
            })
    return blocks

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

    lines = read_memory()
    children_blocks = parse_markdown_to_blocks(lines)
    
    url = "https://api.notion.com/v1/pages"
    
    # Try creating with "Name", if fails we might need to check schema, but usually it's Name or Task.
    # We'll stick to "Name" as it's most standard, but based on error before, maybe the DB was wrong.
    
    payload = {
        "parent": {"database_id": db_id},
        "properties": {
            "Name": {"title": [{"text": {"content": "Tages-Log 17.02.2026"}}]},
            "Status": {"status": {"name": "Done"}},
            "Project": {"relation": [{"id": PROJECT_ID}]}
        },
        "children": children_blocks[:100]
    }
    
    resp = requests.post(url, headers=HEADERS, json=payload)
    if resp.status_code == 200:
        print("✅ Tages-Log in Notion erstellt.")
    else:
        # If Name fails, try Task
        if "Name is not a property" in resp.text:
             payload["properties"].pop("Name")
             payload["properties"]["Task"] = {"title": [{"text": {"content": "Tages-Log 17.02.2026"}}]}
             resp2 = requests.post(url, headers=HEADERS, json=payload)
             if resp2.status_code == 200:
                 print("✅ Tages-Log in Notion erstellt (Property 'Task').")
             else:
                 print(f"❌ Fehler (Retry): {resp2.text}")
        else:
             print(f"❌ Fehler: {resp.text}")

if __name__ == "__main__":
    create_log_entry()
