#!/usr/bin/env python3
"""
add-to-notion.py - Add trend signal to Notion database
Usage: add-to-notion.py <title> <url> <tags> <insight> <image_path>
"""

import sys
import os
import shutil
import json
import requests
from pathlib import Path

def read_api_key():
    """Read Notion API key from secrets file"""
    try:
        with open('/home/clawd/secrets/notion/api_key', 'r') as f:
            return f.read().strip()
    except FileNotFoundError:
        print("Error: Notion API key not found at /home/clawd/secrets/notion/api_key", file=sys.stderr)
        sys.exit(1)

def copy_screenshot_to_public(image_path):
    """Copy screenshot to public directory and return web URL"""
    public_dir = Path('/root/.openclaw/workspace/public/radar-screenshots')
    public_dir.mkdir(parents=True, exist_ok=True)
    
    filename = Path(image_path).name
    dest_path = public_dir / filename
    
    try:
        shutil.copy2(image_path, dest_path)
        web_url = f"https://ce-website-peach.vercel.app/radar-screenshots/{filename}"
        return web_url
    except Exception as e:
        print(f"Error copying screenshot to public directory: {e}", file=sys.stderr)
        sys.exit(1)

def create_notion_page(api_key, title, url, tags, insight, cover_url):
    """Create a Notion page with the trend signal data"""
    database_id = "2ff330c2-8646-81f0-bbd9-ec474393d7a5"
    
    headers = {
        "Authorization": f"Bearer {api_key}",
        "Content-Type": "application/json",
        "Notion-Version": "2022-06-28"
    }
    
    # Parse tags (comma-separated)
    tag_list = [tag.strip() for tag in tags.split(',') if tag.strip()]
    
    data = {
        "parent": {"database_id": database_id},
        "cover": {
            "type": "external",
            "external": {"url": cover_url}
        },
        "properties": {
            "Name": {
                "title": [{"text": {"content": title}}]
            },
            "Link": {
                "url": url
            },
            "Tags": {
                "multi_select": [{"name": tag} for tag in tag_list]
            },
            "Status": {
                "select": {"name": "Approved"}
            },
            "Source Board": {
                "select": {"name": "Radar"}
            },
            "Strategic Insight": {
                "rich_text": [{"text": {"content": insight}}]
            },
            "Positioning Lesson": {
                "rich_text": [{"text": {"content": ""}}]
            },
            "Use Case": {
                "select": None  # Will be set to empty/null
            }
        }
    }
    
    try:
        response = requests.post(
            "https://api.notion.com/v1/pages",
            headers=headers,
            json=data
        )
        
        if response.status_code == 200:
            page_data = response.json()
            page_url = page_data.get('url', 'Unknown')
            print(f"Successfully created Notion page: {page_url}")
            return True
        else:
            print(f"Error creating Notion page: {response.status_code}", file=sys.stderr)
            print(f"Response: {response.text}", file=sys.stderr)
            return False
            
    except Exception as e:
        print(f"Error making request to Notion API: {e}", file=sys.stderr)
        return False

def main():
    if len(sys.argv) != 6:
        print("Usage: add-to-notion.py <title> <url> <tags> <insight> <image_path>", file=sys.stderr)
        sys.exit(1)
    
    title = sys.argv[1]
    url = sys.argv[2]
    tags = sys.argv[3]
    insight = sys.argv[4]
    image_path = sys.argv[5]
    
    # Validate image path exists
    if not os.path.exists(image_path):
        print(f"Error: Image file not found: {image_path}", file=sys.stderr)
        sys.exit(1)
    
    # Read API key
    api_key = read_api_key()
    
    # Copy screenshot to public directory
    cover_url = copy_screenshot_to_public(image_path)
    print(f"Screenshot copied to: {cover_url}")
    
    # Create Notion page
    if create_notion_page(api_key, title, url, tags, insight, cover_url):
        sys.exit(0)
    else:
        sys.exit(1)

if __name__ == "__main__":
    main()