#!/usr/bin/env python3
"""
View and update research pipeline in Notion.

Usage:
    papers                              # Show all papers
    papers --active                     # Show papers in progress
    papers --update "[Journal]" "R&R"        # Update paper stage
"""

import argparse
import json
import os
import sys
import urllib.request
import urllib.error


NOTION_TOKEN = os.environ.get("NOTION_TOKEN")
DATABASE_ID = "YOUR-PIPELINE-DATABASE-ID-HERE"  # Research Pipeline

STAGES = [
    "Idea",
    "Literature Review",
    "Drafting",
    "Internal Review",
    "Submitted",
    "Under Review",
    "R&R",
    "Revising",
    "Accepted",
    "Published",
]


def query_papers():
    """Query papers from Notion."""
    if not NOTION_TOKEN:
        print("❌ NOTION_TOKEN not set")
        sys.exit(1)

    data = {
        "sorts": [
            {"property": "Priority", "direction": "ascending"}
        ]
    }

    req = urllib.request.Request(
        f"https://api.notion.com/v1/databases/{DATABASE_ID}/query",
        data=json.dumps(data).encode("utf-8"),
        headers={
            "Authorization": f"Bearer {NOTION_TOKEN}",
            "Content-Type": "application/json",
            "Notion-Version": "2022-06-28",
        },
        method="POST",
    )

    try:
        with urllib.request.urlopen(req) as response:
            return json.loads(response.read().decode("utf-8"))
    except urllib.error.HTTPError as e:
        error_body = json.loads(e.read().decode("utf-8"))
        print(f"❌ Error: {e.code}")
        print(error_body.get("message", str(error_body)))
        sys.exit(1)


def get_property(page, prop_name, prop_type):
    """Extract property value from a Notion page."""
    prop = page.get("properties", {}).get(prop_name, {})

    if prop_type == "title":
        title_list = prop.get("title", [])
        return title_list[0].get("plain_text", "") if title_list else ""
    elif prop_type == "select":
        select = prop.get("select")
        return select.get("name", "") if select else ""
    elif prop_type == "status":
        status = prop.get("status")
        return status.get("name", "") if status else ""
    elif prop_type == "rich_text":
        text_list = prop.get("rich_text", [])
        return text_list[0].get("plain_text", "") if text_list else ""
    return ""


def update_paper_stage(page_id, new_stage):
    """Update a paper's stage."""
    # Note: Stage might be a status or select property
    data = {
        "properties": {
            "Stage": {"status": {"name": new_stage}}
        }
    }

    req = urllib.request.Request(
        f"https://api.notion.com/v1/pages/{page_id}",
        data=json.dumps(data).encode("utf-8"),
        headers={
            "Authorization": f"Bearer {NOTION_TOKEN}",
            "Content-Type": "application/json",
            "Notion-Version": "2022-06-28",
        },
        method="PATCH",
    )

    try:
        with urllib.request.urlopen(req) as response:
            return True
    except urllib.error.HTTPError as e:
        error_body = json.loads(e.read().decode("utf-8"))
        print(f"❌ Error: {e.code}")
        print(error_body.get("message", str(error_body)))
        return False


def format_paper(page):
    """Format a paper for display."""
    title = get_property(page, "Paper Title", "title")
    stage = get_property(page, "Stage", "status")
    journal = get_property(page, "Target Journal", "rich_text")
    priority = get_property(page, "Priority", "select")
    uni = get_property(page, "University", "select")

    priority_emoji = {"High": "🔴", "Medium": "🟡", "Low": "🟢"}.get(priority, "⚪")

    stage_emoji = {
        "Idea": "💡",
        "Literature Review": "📚",
        "Drafting": "✍️",
        "Internal Review": "👀",
        "Submitted": "📤",
        "Under Review": "⏳",
        "R&R": "🔄",
        "Revising": "✍️",
        "Accepted": "✅",
        "Published": "🎉",
    }.get(stage, "📄")

    line = f"{priority_emoji} {stage_emoji} {title}"
    if stage:
        line += f" [{stage}]"
    if journal:
        line += f" → {journal}"

    return line


def main():
    parser = argparse.ArgumentParser(description="Research pipeline manager")
    parser.add_argument("--active", action="store_true", help="Show only active papers")
    parser.add_argument("--update", nargs=2, metavar=("SEARCH", "STAGE"), help="Update paper stage")
    parser.add_argument("--stages", action="store_true", help="List available stages")

    args = parser.parse_args()

    if args.stages:
        print("Available stages:")
        for s in STAGES:
            print(f"  - {s}")
        return

    if args.update:
        search_term, new_stage = args.update

        # Validate stage
        if new_stage not in STAGES:
            print(f"❌ Invalid stage: {new_stage}")
            print(f"Valid stages: {', '.join(STAGES)}")
            return

        result = query_papers()
        pages = result.get("results", [])

        # Find matching paper
        search_lower = search_term.lower()
        matches = [p for p in pages if search_lower in get_property(p, "Paper Title", "title").lower()]

        if not matches:
            print(f"No papers found matching '{search_term}'")
            return

        if len(matches) == 1:
            page = matches[0]
            title = get_property(page, "Paper Title", "title")
            if update_paper_stage(page["id"], new_stage):
                print(f"✅ Updated: {title} → {new_stage}")
        else:
            print(f"Found {len(matches)} matching papers:")
            for i, page in enumerate(matches, 1):
                title = get_property(page, "Paper Title", "title")
                print(f"{i}. {title}")

            try:
                choice = input("Which one? (number): ").strip()
                idx = int(choice) - 1
                if 0 <= idx < len(matches):
                    page = matches[idx]
                    title = get_property(page, "Paper Title", "title")
                    if update_paper_stage(page["id"], new_stage):
                        print(f"✅ Updated: {title} → {new_stage}")
            except (ValueError, KeyboardInterrupt):
                print("\nCancelled.")
        return

    # List papers
    result = query_papers()
    pages = result.get("results", [])

    if args.active:
        active_stages = ["Literature Review", "Drafting", "Internal Review", "R&R", "Revising"]
        pages = [p for p in pages if get_property(p, "Stage", "status") in active_stages]

    if not pages:
        print("No papers found.")
        return

    print(f"📚 Research Pipeline ({len(pages)} papers)")
    print("-" * 50)

    for page in pages:
        print(format_paper(page))


if __name__ == "__main__":
    main()
