#!/usr/bin/env python3
"""Ingest Zoom summaries and retained transcripts into a local SQLite index."""

import argparse
import json
import sqlite3
from datetime import datetime, timezone
from pathlib import Path

import zoom_mcp


HERE = Path(__file__).resolve().parent


def now() -> str:
    return datetime.now(timezone.utc).isoformat()


def upsert_meeting(db: sqlite3.Connection, item: dict) -> None:
    db.execute(
        """
        INSERT INTO meetings (
          meeting_uuid, meeting_id, topic, host_email, started_at, ended_at, synced_at
        ) VALUES (?, ?, ?, ?, ?, ?, ?)
        ON CONFLICT(meeting_uuid) DO UPDATE SET
          meeting_id=excluded.meeting_id,
          topic=excluded.topic,
          host_email=excluded.host_email,
          started_at=excluded.started_at,
          ended_at=excluded.ended_at,
          synced_at=excluded.synced_at
        """,
        (
            item["meeting_uuid"],
            item.get("meeting_id"),
            item.get("meeting_topic") or "Untitled Zoom meeting",
            item.get("meeting_host_email"),
            item.get("meeting_start_time"),
            item.get("meeting_end_time"),
            now(),
        ),
    )


def sync_meeting(db: sqlite3.Connection, item: dict) -> None:
    meeting_uuid = item["meeting_uuid"]
    upsert_meeting(db, item)

    summary = json.loads(zoom_mcp.get_meeting_summary(meeting_uuid))
    db.execute(
        """
        INSERT INTO summaries (
          meeting_uuid, title, content_markdown, next_steps_json,
          source_url, updated_at, synced_at
        ) VALUES (?, ?, ?, ?, ?, ?, ?)
        ON CONFLICT(meeting_uuid) DO UPDATE SET
          title=excluded.title,
          content_markdown=excluded.content_markdown,
          next_steps_json=excluded.next_steps_json,
          source_url=excluded.source_url,
          updated_at=excluded.updated_at,
          synced_at=excluded.synced_at
        """,
        (
            meeting_uuid,
            summary.get("summary_title"),
            summary.get("summary_content") or summary.get("summary_overview") or "",
            json.dumps(summary.get("next_steps") or []),
            summary.get("summary_doc_url"),
            summary.get("summary_last_modified_time"),
            now(),
        ),
    )

    transcript = json.loads(zoom_mcp.get_meeting_transcript(meeting_uuid, True))
    content = transcript.get("transcript_content") or ""
    if content:
        db.execute(
            """
            INSERT INTO transcripts (
              meeting_uuid, content, format, created_at, synced_at
            ) VALUES (?, ?, 'vtt', ?, ?)
            ON CONFLICT(meeting_uuid) DO UPDATE SET
              content=excluded.content,
              created_at=excluded.created_at,
              synced_at=excluded.synced_at
            """,
            (meeting_uuid, content, transcript.get("transcript_created_time"), now()),
        )

    db.execute("DELETE FROM meeting_search WHERE meeting_uuid = ?", (meeting_uuid,))
    db.execute(
        "INSERT INTO meeting_search (meeting_uuid, topic, summary, transcript) VALUES (?, ?, ?, ?)",
        (
            meeting_uuid,
            item.get("meeting_topic") or "",
            summary.get("summary_content") or summary.get("summary_overview") or "",
            content,
        ),
    )


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("--from-time", required=True, help="RFC 3339, e.g. 2026-07-01T00:00:00Z")
    parser.add_argument("--to-time", required=True, help="RFC 3339, e.g. 2026-08-01T00:00:00Z")
    parser.add_argument("--db", default="zoom-memory.sqlite")
    args = parser.parse_args()

    db = sqlite3.connect(args.db)
    db.executescript((HERE / "schema.sql").read_text())

    token = ""
    synced = 0
    while True:
        page = json.loads(
            zoom_mcp.list_meeting_summaries(
                args.from_time,
                args.to_time,
                page_size=300,
                next_page_token=token,
            )
        )
        for item in page.get("summaries", []):
            sync_meeting(db, item)
            synced += 1
            print(f"synced: {item.get('meeting_topic', item['meeting_uuid'])}")
        token = page.get("next_page_token") or ""
        if not token:
            break

    db.execute(
        """
        INSERT INTO sync_state (source, cursor, last_success_at, last_error)
        VALUES ('zoom', ?, ?, NULL)
        ON CONFLICT(source) DO UPDATE SET
          cursor=excluded.cursor,
          last_success_at=excluded.last_success_at,
          last_error=NULL
        """,
        (args.to_time, now()),
    )
    db.commit()
    db.close()
    print(f"complete: {synced} meeting(s) indexed in {args.db}")


if __name__ == "__main__":
    main()
