#!/usr/bin/env python3
"""
Sync daily memory logs between Local and VPS via Notion.

Creates/updates a daily log page in Notion Bot Memory.
Both Local and VPS Kitt can push their logs, creating a unified view.

Usage: python3 sync-memory-to-notion.py [--source local|vps]
"""

import subprocess
import json
import sys
import os
from datetime import datetime

NOTION_API_KEY_PATH = os.path.expanduser("~/.config/notion/api_key")
BOT_MEMORY_PAGE = "2f1330c2-8646-81c6-8c7b-e328bc6466eb"
MEMORY_DIR = os.path.expanduser("~/clawd/memory")

def get_notion_key():
    with open(NOTION_API_KEY_PATH, 'r') as f:
        return f.read().strip()

def get_today_log():
    """Read today's memory log if it exists."""
    today = datetime.now().strftime("%Y-%m-%d")
    log_path = os.path.join(MEMORY_DIR, f"{today}.md")
    
    if os.path.exists(log_path):
        with open(log_path, 'r') as f:
            return f.read()
    return None

def find_or_create_daily_page(notion_key, date_str, source="local"):
    """Find existing daily sync page or create new one."""
    
    # Search for existing page
    search_payload = {
        "query": f"Daily Sync {date_str}",
        "filter": {"property": "object", "value": "page"}
    }
    
    cmd = [
        "curl", "-s", "-X", "POST",
        "https://api.notion.com/v1/search",
        "-H", f"Authorization: Bearer {notion_key}",
        "-H", "Content-Type: application/json",
        "-H", "Notion-Version: 2022-06-28",
        "-d", json.dumps(search_payload)
    ]
    
    result = subprocess.run(cmd, capture_output=True, text=True)
    data = json.loads(result.stdout)
    
    for page in data.get('results', []):
        title = page.get('properties', {}).get('title', {}).get('title', [{}])
        if title and f"Daily Sync {date_str}" in title[0].get('text', {}).get('content', ''):
            return page['id']
    
    # Create new page
    create_payload = {
        "parent": {"page_id": BOT_MEMORY_PAGE},
        "properties": {
            "title": {"title": [{"text": {"content": f"📅 Daily Sync {date_str}"}}]}
        },
        "children": [
            {"object": "block", "type": "heading_2", "heading_2": {"rich_text": [{"text": {"content": "Local Kitt"}}]}},
            {"object": "block", "type": "paragraph", "paragraph": {"rich_text": [{"text": {"content": "(awaiting sync)"}}]}},
            {"object": "block", "type": "divider", "divider": {}},
            {"object": "block", "type": "heading_2", "heading_2": {"rich_text": [{"text": {"content": "VPS Kitt"}}]}},
            {"object": "block", "type": "paragraph", "paragraph": {"rich_text": [{"text": {"content": "(awaiting sync)"}}]}}
        ]
    }
    
    cmd = [
        "curl", "-s", "-X", "POST",
        "https://api.notion.com/v1/pages",
        "-H", f"Authorization: Bearer {notion_key}",
        "-H", "Content-Type: application/json",
        "-H", "Notion-Version: 2022-06-28",
        "-d", json.dumps(create_payload)
    ]
    
    result = subprocess.run(cmd, capture_output=True, text=True)
    data = json.loads(result.stdout)
    return data.get('id')

def push_log_to_notion(notion_key, page_id, content, source="local"):
    """Push log content to the appropriate section of the daily sync page."""
    
    # Get existing blocks
    cmd = [
        "curl", "-s",
        f"https://api.notion.com/v1/blocks/{page_id}/children",
        "-H", f"Authorization: Bearer {notion_key}",
        "-H", "Notion-Version: 2022-06-28"
    ]
    
    result = subprocess.run(cmd, capture_output=True, text=True)
    data = json.loads(result.stdout)
    
    # Find the block after "Local Kitt" or "VPS Kitt" heading
    target_heading = "Local Kitt" if source == "local" else "VPS Kitt"
    blocks = data.get('results', [])
    
    for i, block in enumerate(blocks):
        if block.get('type') == 'heading_2':
            heading_text = block.get('heading_2', {}).get('rich_text', [{}])[0].get('text', {}).get('content', '')
            if heading_text == target_heading and i + 1 < len(blocks):
                # Found the section, update the next block
                next_block_id = blocks[i + 1]['id']
                
                # Truncate content to fit Notion's 2000 char limit per block
                truncated = content[:1900] + "..." if len(content) > 1900 else content
                
                update_payload = {
                    "paragraph": {
                        "rich_text": [{"text": {"content": truncated}}]
                    }
                }
                
                cmd = [
                    "curl", "-s", "-X", "PATCH",
                    f"https://api.notion.com/v1/blocks/{next_block_id}",
                    "-H", f"Authorization: Bearer {notion_key}",
                    "-H", "Content-Type: application/json",
                    "-H", "Notion-Version: 2022-06-28",
                    "-d", json.dumps(update_payload)
                ]
                
                subprocess.run(cmd, capture_output=True, text=True)
                return True
    
    return False

def main():
    source = "local"
    if "--source" in sys.argv:
        idx = sys.argv.index("--source")
        if idx + 1 < len(sys.argv):
            source = sys.argv[idx + 1]
    
    today = datetime.now().strftime("%Y-%m-%d")
    print(f"Memory Sync ({source}) - {today}")
    print("=" * 40)
    
    notion_key = get_notion_key()
    
    # Get today's log
    log_content = get_today_log()
    if not log_content:
        print(f"No log found for today ({today})")
        # Create a minimal entry
        log_content = f"# {today} - {source.upper()} Kitt\n\nNo detailed log for today."
    
    # Find or create daily sync page
    print("Finding/creating daily sync page...")
    page_id = find_or_create_daily_page(notion_key, today, source)
    
    if not page_id:
        print("ERROR: Could not find or create daily sync page")
        return
    
    print(f"Page ID: {page_id}")
    
    # Push log content
    print(f"Pushing {source} log...")
    timestamp = datetime.now().strftime("%H:%M")
    content_with_ts = f"**Last sync: {timestamp}**\n\n{log_content}"
    
    if push_log_to_notion(notion_key, page_id, content_with_ts, source):
        print(f"✅ {source.upper()} log synced to Notion")
    else:
        print(f"⚠️ Could not update {source} section")

if __name__ == "__main__":
    main()
