#!/usr/bin/env python3
"""
Sync ag-wiki to Notion.
Runs daily: reads wiki markdown files, updates Notion memory page.
"""

import subprocess
import urllib.request
import json
import os
from datetime import datetime

NOTION_TOKEN = "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"
MEMORY_PAGE_ID = "34289b86-f0bd-8174-ba07-d213cc0ed8d3"
WIKI_DIR = "/srv/wiki"

def notion_request(method, path, data=None):
    url = f"https://api.notion.com/v1{path}"
    headers = {
        "Authorization": f"Bearer {NOTION_TOKEN}",
        "Notion-Version": "2022-06-28",
        "Content-Type": "application/json",
    }
    body = json.dumps(data).encode() if data else None
    req = urllib.request.Request(url, data=body, headers=headers, method=method)
    try:
        resp = urllib.request.urlopen(req)
        return json.loads(resp.read())
    except urllib.error.HTTPError as e:
        print(f"Notion API error {e.code}: {e.read().decode()}")
        return None

def git_pull():
    result = subprocess.run(["git", "pull"], cwd=WIKI_DIR, capture_output=True, text=True)
    print("git pull:", result.stdout.strip() or result.stderr.strip())

def read_wiki():
    projects = {}
    for name in ["lunar-hubble", "ad-analytics", "pediatric-news", "zest-content"]:
        path = os.path.join(WIKI_DIR, name, "index.md")
        if os.path.exists(path):
            projects[name] = open(path).read()
    readme = open(os.path.join(WIKI_DIR, "README.md")).read()
    return readme, projects

def get_git_log():
    result = subprocess.run(
        ["git", "log", "--oneline", "-10", "--all"],
        cwd=WIKI_DIR, capture_output=True, text=True
    )
    return result.stdout.strip()

def clear_page_blocks():
    blocks = notion_request("GET", f"/blocks/{MEMORY_PAGE_ID}/children")
    if not blocks:
        return
    for b in blocks.get("results", []):
        notion_request("DELETE", f"/blocks/{b['id']}")

def update_notion(readme, projects, git_log):
    now = datetime.now().strftime("%Y-%m-%d %H:%M")

    children = [
        {
            "object": "block", "type": "callout",
            "callout": {
                "icon": {"type": "emoji", "emoji": "🔄"},
                "rich_text": [{"type": "text", "text": {"content": f"Синхронізовано з ag-wiki. Оновлено: {now}"}}],
                "color": "blue_background"
            }
        },
        {
            "object": "block", "type": "heading_1",
            "heading_1": {"rich_text": [{"type": "text", "text": {"content": "📁 Проекти"}}]}
        },
    ]

    project_meta = {
        "lunar-hubble": ("🌙", "TypeScript, React 18, Vite, D3.js, Supabase, Telegraf, Gemini AI"),
        "ad-analytics": ("📊", "Node.js, Express, Google Ads API, BigQuery, OAuth2"),
        "pediatric-news": ("🏥", "Node.js ESM, Gemini AI, Firestore, GCS, Telegraf, Docker"),
        "zest-content": ("🍋", "Next.js 16, React 19, TypeScript, Tailwind CSS 4, Gemini AI"),
    }

    for name, content in projects.items():
        emoji, stack = project_meta.get(name, ("📁", ""))
        # Check if content has real info (not just "To be documented")
        has_content = "To be documented" not in content and len(content.strip()) > 50
        status = "🟢 Задокументовано" if has_content else "🟡 В розробці"

        children.append({
            "object": "block", "type": "heading_2",
            "heading_2": {"rich_text": [{"type": "text", "text": {"content": f"{emoji} {name}"}}]}
        })
        children.append({
            "object": "block", "type": "table",
            "table": {
                "table_width": 2, "has_column_header": False, "has_row_header": True,
                "children": [
                    {"type": "table_row", "table_row": {"cells": [[{"type": "text", "text": {"content": "Стек"}}], [{"type": "text", "text": {"content": stack}}]]}},
                    {"type": "table_row", "table_row": {"cells": [[{"type": "text", "text": {"content": "Статус"}}], [{"type": "text", "text": {"content": status}}]]}},
                    {"type": "table_row", "table_row": {"cells": [[{"type": "text", "text": {"content": "Вікі"}}], [{"type": "text", "text": {"content": f"/srv/wiki/{name}/"}}]]}},
                ]
            }
        })

        if has_content:
            # Add actual content (truncated)
            snippet = content[:500].strip()
            children.append({
                "object": "block", "type": "paragraph",
                "paragraph": {"rich_text": [{"type": "text", "text": {"content": snippet}, "annotations": {"color": "gray"}}]}
            })

    # Git log
    children.append({
        "object": "block", "type": "heading_1",
        "heading_1": {"rich_text": [{"type": "text", "text": {"content": "📝 Останні зміни (git log)"}}]}
    })
    children.append({
        "object": "block", "type": "code",
        "code": {
            "language": "plain text",
            "rich_text": [{"type": "text", "text": {"content": git_log or "Немає змін"}}]
        }
    })

    clear_page_blocks()
    result = notion_request("PATCH", f"/blocks/{MEMORY_PAGE_ID}/children", {"children": children})
    if result:
        print(f"✅ Notion updated at {now}")
    else:
        print("❌ Failed to update Notion")

if __name__ == "__main__":
    print(f"Starting sync at {datetime.now()}")
    git_pull()
    readme, projects = read_wiki()
    git_log = get_git_log()
    update_notion(readme, projects, git_log)
    print("Done.")
