# AGENTS.md - Project Analysis

This document provides a comprehensive analysis of the Notion to Markdown Exporter project. This is a Python Flask application that exports Notion page content to Markdown format using the Notion API. The application provides a RESTful API that can convert complete Notion pages with all their block types into properly formatted Markdown text.

## Coding Instructions
1. If using Python, do not rely on specific versions of python libraries. For dependencies, always use package="*" for latest version, unless necessary to be specific. Code you write, should be version agnostic as much as possible.
2. Existing packages are the preferred path to add new functionality - only add new packages if a request can not be facilitated with the existing code-base.
3. The developer machine is using Windows 11 & Power Shell from within VScode - note that for any tool use that sends console commands. (example - "&&" is not available, ";" is - for execution of multiple commands)
4. Python Specific Instructions:
	a. Always use type annotations
	b. Never use catchall except ("except Exception") unless it's the best solution in that situation
	c. For making https calls (if needed), use httpx - not requests
	d. For parsing (if needed), use Lark
	e. Use current Python syntax, unless asked otherwise
	f. Prefer logging over printing, use colors either way.
	g. Prefer to use list comprehensions when possible
	h. Don't create tests files unless explicitly asked by the user
5. Large or complex functions should be created as separate python files - no python file should be extremely long or too complicated with multiple functions. Try to use clear logic and naming convention when deciding how to build project files and folders.
6. DO NOT write in-file comments, ever - if you want to add comments related to the code, append them in the project-analysis.md file or AGENTS.md file.

## Guiding Principles
- keep files under 300 lines where possible
- already read the files in full when approaching a task
- develop in a modular and reusable way
- before making changes always read all the relevant files according to this document
- don't make assumptions and jump to conclusions, ask for clarifications
- consider multiple approaches to problem solving, suggest few paths

## File Analysis

### app.py
**Purpose**: Main Flask application entry point that provides the web API interface for the Notion to Markdown conversion service.

**Connections**: 
- Imports: `os`, `logging`, `flask` (Flask, jsonify, request), `dotenv` (load_dotenv), `notion_to_md` (export_notion_page_to_markdown)
- Uses environment variables: `NOTION_TOKEN`, `PORT`, `FLASK_ENV`
- Calls: `export_notion_page_to_markdown()` function from notion_to_md module

**Functions/Classes**:
- `export_page(page_id: str)`: Main API endpoint that handles GET requests to `/page/<page_id>`, validates page ID format, cleans the ID, calls the conversion function, and returns Markdown content as plain text response
- `health_check()`: Health check endpoint at `/health` that returns service status
- `home()`: Root endpoint at `/` that provides API usage instructions and available endpoints
- `not_found(error)`: 404 error handler that returns JSON error response
- `internal_error(error)`: 500 error handler that logs errors and returns JSON error response
- Main execution block: Validates NOTION_TOKEN environment variable and starts Flask server

**Notable Settings**:
- Server runs on host `0.0.0.0` (all interfaces)
- Default port is 5000 (configurable via PORT env var)
- Debug mode enabled when FLASK_ENV=development
- Logging configured at INFO level with timestamp format
- Returns Markdown content with `text/markdown; charset=utf-8` content type

### notion_to_md.py
**Purpose**: Core conversion logic that handles communication with Notion API and converts Notion blocks to Markdown format.

**Connections**:
- Imports: `os`, `logging`, `typing` (List, Dict, Any, Optional), `notion_client` (Client), `notion_client.helpers` (collect_paginated_api)
- Uses environment variables: `NOTION_TOKEN`
- External API: Notion API via notion-client library

**Functions/Classes**:
- `NotionToMarkdown` class: Main converter class that handles all conversion logic
  - `__init__(self, token: str)`: Initializes Notion client with authentication token
  - `get_page_content_as_markdown(self, page_id: str) -> str`: Main public method that retrieves page info and all blocks, then converts to Markdown
  - `_convert_blocks_to_markdown(self, blocks: List[Dict[str, Any]]) -> str`: Converts list of Notion blocks to Markdown, handles all block types and child blocks recursively
  - `_extract_rich_text(self, rich_text_array: List[Dict[str, Any]]) -> str`: Extracts and formats rich text with annotations (bold, italic, strikethrough, code, links)
  - Block conversion methods (all return formatted Markdown strings):
    - `_convert_paragraph()`: Plain text paragraphs
    - `_convert_heading()`: H1, H2, H3 headings with # syntax
    - `_convert_bulleted_list_item()`: Bulleted lists with - syntax
    - `_convert_numbered_list_item()`: Numbered lists with 1. syntax
    - `_convert_todo()`: To-do items with checkbox syntax
    - `_convert_toggle()`: Toggle blocks as HTML details/summary
    - `_convert_quote()`: Quote blocks with > syntax
    - `_convert_code()`: Code blocks with language-specific syntax highlighting
    - `_convert_callout()`: Callout blocks with icon and quote syntax
    - `_convert_image()`: Images with alt text and URL
    - `_convert_file()`: File attachments as links
    - `_convert_bookmark()`: Bookmarks as links
    - `_convert_embed()`: Embedded content as links
    - `_convert_table()`: Tables in Markdown table format with header support
- `export_notion_page_to_markdown(page_id: str, token: Optional[str] = None) -> str`: Standalone function that creates converter instance and exports page

**Notable Settings**:
- Logging configured at INFO level
- Handles pagination automatically for large pages
- Supports nested/child blocks with indentation
- Comprehensive error handling with logging
- Supports all major Notion block types

### requirements.txt
**Purpose**: Python package dependencies specification file.

**Connections**: 
- Used by pip for package installation
- Referenced in README.md setup instructions

**Notable Settings**:
- `flask=*`: Web framework for API endpoints (latest version)
- `notion-client=*`: Official Notion API client library (latest version)
- `python-dotenv=*`: Environment variable loading from .env files (latest version)
- All dependencies use wildcard versioning for latest versions

### .env.example
**Purpose**: Template file showing required environment variables for the application.

**Connections**:
- Template for creating actual .env file
- Referenced in README.md setup instructions
- Used by python-dotenv in app.py

**Notable Settings**:
- `NOTION_TOKEN`: Placeholder for Notion integration token (required for API access)


## Architecture Overview

The application follows a clean separation of concerns:

1. **app.py**: Web layer - handles HTTP requests, validation, error handling, and responses
2. **notion_to_md.py**: Business logic layer - handles Notion API communication and Markdown conversion
3. **requirements.txt**: Dependency management
4. **.env.example**: Configuration template
5. **README.md**: Documentation and usage guide

The conversion process flow:
1. Flask receives GET request with page_id
2. Page ID is validated and cleaned
3. `export_notion_page_to_markdown()` is called
4. `NotionToMarkdown` class retrieves page data from Notion API
5. All blocks are converted to Markdown recursively
6. Formatted Markdown is returned as plain text response

The application supports comprehensive Notion block types including text formatting, lists, headings, code blocks, images, tables, and nested content with proper indentation.
