#!/usr/bin/env python3
"""
Import inspo folder scan results to Notion.
Reads the JSON from Mac scan, imports to Notion Inspiration database.
"""

import json
import requests
import time
import sys
from pathlib import Path

# Config
NOTION_API_KEY_PATH = "/home/clawd/secrets/notion/api_key"
DATABASE_ID = "2ff330c28646-81f0-bbd9-ec474393d7a5".replace("-", "")  # Inspiration DB
SCAN_RESULTS_PATH = sys.argv[1] if len(sys.argv) > 1 else "/tmp/inspo_scan_results.json"

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

def create_notion_page(session, db_id, properties):
    """Create a single page in Notion database."""
    url = "https://api.notion.com/v1/pages"
    payload = {
        "parent": {"database_id": db_id},
        "properties": properties
    }
    resp = session.post(url, json=payload)
    return resp.status_code == 200, resp.text

def build_properties(item, item_type, source_folder):
    """Build Notion properties for an item."""
    props = {
        "Name": {"title": [{"text": {"content": item.get("title", item.get("filename", "Untitled"))[:2000]}}]},
        "Source Board": {"select": {"name": f"Desktop/inspo/{source_folder}" if source_folder != "root" else "Desktop/inspo"}},
    }
    
    # Add URL if available
    if item.get("url"):
        props["Link"] = {"url": item["url"]}
    
    # Add tags based on type and folder
    tags = []
    if item_type == "webloc":
        tags.append("bookmark")
    elif item_type == "image":
        tags.append("image")
        tags.append(item.get("type", "unknown"))
    elif item_type == "pdf":
        tags.append("pdf")
        tags.append("document")
    elif item_type == "html":
        tags.append("saved-page")
    
    # Add folder as tag if not root
    if source_folder != "root":
        folder_tag = source_folder.replace("/", "-").lower()
        tags.append(folder_tag)
    
    if tags:
        props["Tags"] = {"multi_select": [{"name": t} for t in tags[:10]]}  # Limit to 10 tags
    
    return props

def main():
    print(f"Loading scan results from {SCAN_RESULTS_PATH}...")
    with open(SCAN_RESULTS_PATH) as f:
        data = json.load(f)
    
    print(f"Found {data['metadata']['total_items']} items to import")
    
    # Setup Notion session
    api_key = get_notion_key()
    session = requests.Session()
    session.headers.update({
        "Authorization": f"Bearer {api_key}",
        "Content-Type": "application/json",
        "Notion-Version": "2022-06-28"
    })
    
    # Format database ID
    db_id = DATABASE_ID
    if len(db_id) == 32:
        db_id = f"{db_id[:8]}-{db_id[8:12]}-{db_id[12:16]}-{db_id[16:20]}-{db_id[20:]}"
    
    print(f"Importing to database: {db_id}")
    
    success = 0
    failed = 0
    
    # Import weblocs
    print(f"\nImporting {len(data['weblocs'])} weblocs...")
    for item in data["weblocs"]:
        props = build_properties(item, "webloc", item["folder"])
        ok, _ = create_notion_page(session, db_id, props)
        if ok:
            success += 1
        else:
            failed += 1
        time.sleep(0.35)  # Rate limiting
        if success % 10 == 0:
            print(f"  Progress: {success} imported...")
    
    # Import images
    print(f"\nImporting {len(data['images'])} images...")
    for item in data["images"]:
        props = build_properties(item, "image", item["folder"])
        ok, _ = create_notion_page(session, db_id, props)
        if ok:
            success += 1
        else:
            failed += 1
        time.sleep(0.35)
        if success % 10 == 0:
            print(f"  Progress: {success} imported...")
    
    # Import PDFs
    print(f"\nImporting {len(data['pdfs'])} PDFs...")
    for item in data["pdfs"]:
        props = build_properties(item, "pdf", item["folder"])
        ok, _ = create_notion_page(session, db_id, props)
        if ok:
            success += 1
        else:
            failed += 1
        time.sleep(0.35)
    
    # Import HTML files
    print(f"\nImporting {len(data['html_files'])} HTML files...")
    for item in data["html_files"]:
        props = build_properties(item, "html", item["folder"])
        ok, _ = create_notion_page(session, db_id, props)
        if ok:
            success += 1
        else:
            failed += 1
        time.sleep(0.35)
    
    print(f"\n{'='*40}")
    print(f"COMPLETE")
    print(f"  Success: {success}")
    print(f"  Failed:  {failed}")
    print(f"  Total:   {success + failed}")
    
    return 0 if failed == 0 else 1

if __name__ == "__main__":
    exit(main())
