import requests
import json
import os
import re
import sys

TOKEN_FILE = 'notion_api_key.txt'
PARENT_PAGE_ID = "2e088f42-8544-8024-8289-deb383da3818"

def parse_markdown_to_blocks(md_content):
    blocks = []
    lines = md_content.split('\n')
    
    in_code_block = False
    code_content = []
    
    for line in lines:
        stripped = line.strip()
        
        if stripped.startswith("```"):
            if in_code_block:
                blocks.append({
                    "object": "block",
                    "type": "code",
                    "code": {
                        "rich_text": [{"type": "text", "text": {"content": '\n'.join(code_content)}}],
                        "language": "plain text"
                    }
                })
                code_content = []
                in_code_block = False
            else:
                in_code_block = True
            continue
            
        if in_code_block:
            code_content.append(line)
            continue

        if not stripped:
            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 stripped.startswith("* ") or stripped.startswith("- "):
            content = stripped[2:]
            blocks.append({
                "object": "block",
                "type": "bulleted_list_item",
                "bulleted_list_item": {"rich_text": [{"type": "text", "text": {"content": content}}]}}
            )
        elif re.match(r"^\d+\.", stripped):
            content = re.sub(r"^\d+\.\s*", "", stripped)
            blocks.append({
                "object": "block",
                "type": "numbered_list_item",
                "numbered_list_item": {"rich_text": [{"type": "text", "text": {"content": content}}]}}
            )
        elif stripped.startswith("|"):
             blocks.append({
                "object": "block",
                "type": "code",
                "code": {
                    "rich_text": [{"type": "text", "text": {"content": line}}],
                    "language": "plain text"
                }
            })
        else:
            blocks.append({
                "object": "block",
                "type": "paragraph",
                "paragraph": {"rich_text": [{"type": "text", "text": {"content": line}}]}}
            )
            
    return blocks

def upload_doc(token, file_path):
    try:
        with open(file_path, 'r') as f:
            content = f.read()
    except FileNotFoundError:
        print(f"Error: Could not find '{file_path}'")
        return

    title = os.path.basename(file_path)
    if content.startswith("# "):
        title = content.split('\n')[0][2:].strip()

    print(f"Parsing '{file_path}'...")
    children_blocks = parse_markdown_to_blocks(content)
    
    url = "https://api.notion.com/v1/pages"
    headers = {
        "Authorization": f"Bearer {token}",
        "Notion-Version": "2022-06-28",
        "Content-Type": "application/json"
    }

    payload = {
        "parent": { "page_id": PARENT_PAGE_ID },
        "properties": {
            "title": [{"text": {"content": f"📘 {title}"}}] 
        },
        "children": children_blocks[:100]
    }

    print(f"Uploading '{title}' to Notion...")
    
    try:
        response = requests.post(url, headers=headers, json=payload)
        response.raise_for_status()
        data = response.json()
        print(f"SUCCESS: {data.get('url')}")
    except Exception as e:
        print(f"ERROR: {e}")

if __name__ == "__main__":
    if len(sys.argv) < 2:
        print("Usage: python sync_docs_to_notion.py <filename>")
        sys.exit(1)
        
    try:
        with open(TOKEN_FILE, 'r') as f:
            token = f.read().strip()
    except FileNotFoundError:
        print(f"Error: Could not find '{TOKEN_FILE}'")
        sys.exit(1)

    upload_doc(token, sys.argv[1])