"""bmadnotion CLI - Command line interface for BMAD to Notion sync."""

from pathlib import Path

import click
from dotenv import load_dotenv
from notion_client import Client

from bmadnotion import __version__
from bmadnotion.config import ConfigNotFoundError, TokenNotFoundError, load_config
from bmadnotion.store import Store

# Import NotionClient from marknotion for use in commands
try:
    from marknotion import NotionClient
except ImportError:
    NotionClient = None  # type: ignore

# Load .env file if present (supports NOTION_TOKEN in .env)
load_dotenv()


def get_project_root() -> Path:
    """Get the project root (current working directory)."""
    return Path.cwd()


@click.group()
@click.version_option(version=__version__, prog_name="bmadnotion")
def cli():
    """Sync BMAD project artifacts to Notion.

    bmadnotion syncs your BMAD project's planning artifacts and sprint
    tracking to Notion, keeping your documentation and progress in sync.
    """
    pass


@cli.command()
@click.option("--project", "-p", help="Project name")
@click.option("--force", "-f", is_flag=True, help="Overwrite existing config")
def init(project: str | None, force: bool):
    """Initialize bmadnotion configuration.

    Creates a .bmadnotion.yaml configuration file in the current directory.
    """
    project_root = get_project_root()
    config_path = project_root / ".bmadnotion.yaml"

    # Check if config already exists
    if config_path.exists() and not force:
        click.echo(f"Configuration file already exists: {config_path}")
        click.echo("Use --force to overwrite.")
        return

    # Use project name from option or directory name
    if not project:
        project = project_root.name

    click.echo(f"Initializing bmadnotion for project: {project}")

    # Generate default configuration
    config_content = f'''# bmadnotion configuration
# Generated by: bmadnotion init

project: {project}

notion:
  # Environment variable containing your Notion API token
  token_env: NOTION_TOKEN
  # Your Notion workspace page ID (for reference)
  workspace_page_id: "your-workspace-page-id"

# Page Sync: Sync planning artifacts to Notion Pages
page_sync:
  enabled: true
  # Parent page ID (fallback if Projects database not configured)
  # When Projects database is configured, documents become sub-pages of the Project row
  parent_page_id: "your-parent-page-id"
  documents:
    - path: "prd.md"
      title: "PRD - {project}"
    - path: "architecture.md"
      title: "Architecture - {project}"
    - path: "ux-design-specification.md"
      title: "UX Design - {project}"

# Database Sync: Sync sprint status to Notion Databases
database_sync:
  enabled: true
  # Projects database (from Agile template)
  projects:
    database_id: "your-projects-database-id"
    key_property: "BMADProject"
    name_property: "Project name"
  # Sprints database (for Epics)
  sprints:
    database_id: "your-sprints-database-id"
    key_property: "BMADEpic"
    status_mapping:
      backlog: "Not Started"
      in-progress: "In Progress"
      done: "Done"
  # Tasks database (for Stories)
  tasks:
    database_id: "your-tasks-database-id"
    key_property: "BMADStory"
    status_mapping:
      backlog: "Backlog"
      ready-for-dev: "Ready"
      in-progress: "In Progress"
      review: "Review"
      done: "Done"

# Run 'bmad setup-db' after configuring database IDs to add required fields
'''

    config_path.write_text(config_content)
    click.echo(f"Created {config_path}")
    click.echo("")
    click.echo("Next steps:")
    click.echo("  1. Set your NOTION_TOKEN environment variable")
    click.echo("  2. Update the page/database IDs in .bmadnotion.yaml")
    click.echo("  3. Run 'bmad setup-db' to add sync key fields")
    click.echo("  4. Run 'bmad sync' to sync your project")


def _get_or_create_project(
    notion_client: Client,
    store: Store,
    config,
    dry_run: bool = False,
) -> str | None:
    """Get or create the Project row and return its page ID.

    Args:
        notion_client: Official notion-client instance (for database operations).
        store: SQLite store for tracking sync state.
        config: Loaded configuration.
        dry_run: If True, don't create anything.

    Returns:
        Notion page ID of the Project row, or None if Projects database not configured.
    """
    from bmadnotion.project_sync import ProjectSyncEngine

    db_config = config.database_sync.projects
    if not db_config.database_id:
        return None

    engine = ProjectSyncEngine(notion_client, store, config)
    page_id, was_created = engine.get_or_create_project(dry_run=dry_run)

    if was_created and not dry_run:
        click.echo(f"Created Project row: {config.project}")
    elif was_created:
        click.echo(f"[DRY RUN] Would create Project row: {config.project}")

    return page_id


@cli.group(invoke_without_command=True)
@click.option("--force", "-f", is_flag=True, help="Force full sync, ignore cache")
@click.option("--dry-run", is_flag=True, help="Preview changes without syncing")
@click.pass_context
def sync(ctx, force: bool, dry_run: bool):
    """Sync artifacts to Notion.

    Without a subcommand, syncs all artifacts (both pages and database).
    """
    ctx.ensure_object(dict)
    ctx.obj["force"] = force
    ctx.obj["dry_run"] = dry_run

    if ctx.invoked_subcommand is None:
        # No subcommand given, sync all
        _sync_all(force=force, dry_run=dry_run)


def _sync_all(force: bool, dry_run: bool):
    """Sync all artifacts (pages and database) with shared Project context."""
    from bmadnotion.db_sync import DbSyncEngine
    from bmadnotion.page_sync import PageSyncEngine
    from bmadnotion.scanner import SprintStatusNotFoundError

    project_root = get_project_root()

    # Load configuration
    try:
        config = load_config(project_root)
    except ConfigNotFoundError as e:
        click.echo(f"Error: {e}", err=True)
        raise SystemExit(1)

    # Get Notion token
    try:
        token = config.get_notion_token()
    except TokenNotFoundError as e:
        click.echo(f"Error: {e}", err=True)
        raise SystemExit(1)

    # Create clients
    if NotionClient is None:
        click.echo("Error: marknotion is not installed.", err=True)
        raise SystemExit(1)

    marknotion_client = NotionClient(token=token)
    notion_client = Client(auth=token)
    store = Store(project_root)

    mode = "[DRY RUN] " if dry_run else ""

    # Get or create Project row first
    project_page_id = None
    if config.database_sync.enabled and config.database_sync.projects.database_id:
        click.echo(f"{mode}Ensuring Project row exists...")
        project_page_id = _get_or_create_project(notion_client, store, config, dry_run)

    # Sync pages
    if config.page_sync.enabled:
        click.echo(f"{mode}Syncing pages...")
        page_engine = PageSyncEngine(marknotion_client, store, config)
        page_result = page_engine.sync(
            force=force,
            dry_run=dry_run,
            project_page_id=project_page_id,
        )

        if dry_run:
            click.echo(f"  Would create: {page_result.created}")
            click.echo(f"  Would update: {page_result.updated}")
            click.echo(f"  Would skip: {page_result.skipped}")
        else:
            click.echo(f"  Created: {page_result.created}")
            click.echo(f"  Updated: {page_result.updated}")
            click.echo(f"  Skipped: {page_result.skipped}")

        if page_result.failed > 0:
            click.echo(f"  Failed: {page_result.failed}", err=True)
            for error in page_result.errors:
                click.echo(f"    - {error}", err=True)

    # Sync database
    if config.database_sync.enabled:
        click.echo(f"{mode}Syncing database...")
        db_engine = DbSyncEngine(marknotion_client, store, config)

        try:
            db_result = db_engine.sync(
                force=force,
                dry_run=dry_run,
                project_page_id=project_page_id,
            )

            click.echo("")
            click.echo("Epics (Sprints):")
            if dry_run:
                click.echo(f"  Would create: {db_result.epics_created}")
                click.echo(f"  Would update: {db_result.epics_updated}")
                click.echo(f"  Would skip: {db_result.epics_skipped}")
            else:
                click.echo(f"  Created: {db_result.epics_created}")
                click.echo(f"  Updated: {db_result.epics_updated}")
                click.echo(f"  Skipped: {db_result.epics_skipped}")

            click.echo("")
            click.echo("Stories (Tasks):")
            if dry_run:
                click.echo(f"  Would create: {db_result.stories_created}")
                click.echo(f"  Would update: {db_result.stories_updated}")
                click.echo(f"  Would skip: {db_result.stories_skipped}")
            else:
                click.echo(f"  Created: {db_result.stories_created}")
                click.echo(f"  Updated: {db_result.stories_updated}")
                click.echo(f"  Skipped: {db_result.stories_skipped}")

            if db_result.epics_failed > 0 or db_result.stories_failed > 0:
                click.echo("")
                click.echo(
                    f"Failed: {db_result.epics_failed + db_result.stories_failed}",
                    err=True,
                )
                for error in db_result.errors:
                    click.echo(f"  - {error}", err=True)

        except SprintStatusNotFoundError as e:
            click.echo(f"  Warning: {e}")

    click.echo("")
    click.echo("Done.")


@sync.command("pages")
@click.option("--force", "-f", is_flag=True, help="Force full sync, ignore cache")
@click.option("--dry-run", is_flag=True, help="Preview changes without syncing")
def sync_pages(force: bool, dry_run: bool):
    """Sync planning artifacts to Notion Pages.

    Syncs documents like PRD, Architecture, and UX Design to Notion pages.
    Documents are created as sub-pages of the Project row if configured.
    """
    from bmadnotion.page_sync import PageSyncEngine

    project_root = get_project_root()

    # Load configuration
    try:
        config = load_config(project_root)
    except ConfigNotFoundError as e:
        click.echo(f"Error: {e}", err=True)
        raise SystemExit(1)

    # Check if page sync is enabled
    if not config.page_sync.enabled:
        click.echo("Page sync is disabled in configuration.")
        return

    # Get Notion token
    try:
        token = config.get_notion_token()
    except TokenNotFoundError as e:
        click.echo(f"Error: {e}", err=True)
        raise SystemExit(1)

    # Create clients
    if NotionClient is None:
        click.echo("Error: marknotion is not installed.", err=True)
        raise SystemExit(1)

    marknotion_client = NotionClient(token=token)
    notion_client = Client(auth=token)
    store = Store(project_root)

    mode = "[DRY RUN] " if dry_run else ""

    # Get or create Project row
    project_page_id = _get_or_create_project(notion_client, store, config, dry_run)

    # Perform sync
    click.echo(f"{mode}Syncing pages...")
    engine = PageSyncEngine(marknotion_client, store, config)
    result = engine.sync(
        force=force,
        dry_run=dry_run,
        project_page_id=project_page_id,
    )

    # Display results
    if dry_run:
        click.echo(f"Would create: {result.created}")
        click.echo(f"Would update: {result.updated}")
        click.echo(f"Would skip: {result.skipped}")
    else:
        click.echo(f"Created: {result.created}")
        click.echo(f"Updated: {result.updated}")
        click.echo(f"Skipped: {result.skipped}")

    if result.failed > 0:
        click.echo(f"Failed: {result.failed}", err=True)
        for error in result.errors:
            click.echo(f"  - {error}", err=True)

    click.echo("Done.")


@sync.command("db")
@click.option("--force", "-f", is_flag=True, help="Force full sync, ignore cache")
@click.option("--dry-run", is_flag=True, help="Preview changes without syncing")
def sync_db(force: bool, dry_run: bool):
    """Sync sprint status to Notion Database.

    Syncs Epics and Stories from sprint-status.yaml to Notion databases.
    Stories are linked to both their Epic (Sprint) and the Project.
    """
    from bmadnotion.db_sync import DbSyncEngine
    from bmadnotion.scanner import SprintStatusNotFoundError

    project_root = get_project_root()

    # Load configuration
    try:
        config = load_config(project_root)
    except ConfigNotFoundError as e:
        click.echo(f"Error: {e}", err=True)
        raise SystemExit(1)

    # Check if database sync is enabled
    if not config.database_sync.enabled:
        click.echo("Database sync is disabled in configuration.")
        return

    # Get Notion token
    try:
        token = config.get_notion_token()
    except TokenNotFoundError as e:
        click.echo(f"Error: {e}", err=True)
        raise SystemExit(1)

    # Create clients
    if NotionClient is None:
        click.echo("Error: marknotion is not installed.", err=True)
        raise SystemExit(1)

    marknotion_client = NotionClient(token=token)
    notion_client = Client(auth=token)
    store = Store(project_root)

    mode = "[DRY RUN] " if dry_run else ""

    # Get or create Project row
    project_page_id = _get_or_create_project(notion_client, store, config, dry_run)

    # Perform sync
    click.echo(f"{mode}Syncing database...")
    engine = DbSyncEngine(marknotion_client, store, config)

    try:
        result = engine.sync(
            force=force,
            dry_run=dry_run,
            project_page_id=project_page_id,
        )
    except SprintStatusNotFoundError as e:
        click.echo(f"Error: {e}", err=True)
        raise SystemExit(1)

    # Display results
    click.echo("")
    click.echo("Epics (Sprints):")
    if dry_run:
        click.echo(f"  Would create: {result.epics_created}")
        click.echo(f"  Would update: {result.epics_updated}")
        click.echo(f"  Would skip: {result.epics_skipped}")
    else:
        click.echo(f"  Created: {result.epics_created}")
        click.echo(f"  Updated: {result.epics_updated}")
        click.echo(f"  Skipped: {result.epics_skipped}")

    click.echo("")
    click.echo("Stories (Tasks):")
    if dry_run:
        click.echo(f"  Would create: {result.stories_created}")
        click.echo(f"  Would update: {result.stories_updated}")
        click.echo(f"  Would skip: {result.stories_skipped}")
    else:
        click.echo(f"  Created: {result.stories_created}")
        click.echo(f"  Updated: {result.stories_updated}")
        click.echo(f"  Skipped: {result.stories_skipped}")

    if result.epics_failed > 0 or result.stories_failed > 0:
        click.echo("")
        click.echo(f"Failed: {result.epics_failed + result.stories_failed}", err=True)
        for error in result.errors:
            click.echo(f"  - {error}", err=True)

    click.echo("")
    click.echo("Done.")


@cli.command()
def status():
    """Show sync status.

    Displays the current sync state, showing what's changed locally
    and what needs to be synced to Notion.
    """
    from bmadnotion.scanner import BMADScanner, SprintStatusNotFoundError

    project_root = get_project_root()

    # Load configuration
    try:
        config = load_config(project_root)
    except ConfigNotFoundError as e:
        click.echo(f"Error: {e}", err=True)
        raise SystemExit(1)

    store = Store(project_root)
    scanner = BMADScanner(config)

    click.echo(f"Project: {config.project}")
    click.echo("")

    # Page sync status
    if config.page_sync.enabled:
        click.echo("=== Page Sync (Planning Artifacts) ===")
        documents = scanner.scan_documents()

        synced = 0
        pending = 0
        changed = 0

        for doc in documents:
            state = store.get_page_state(doc.path.name)
            if state is None:
                pending += 1
                click.echo(f"  [NEW] {doc.path.name}")
            elif state.content_hash != doc.content_hash:
                changed += 1
                click.echo(f"  [CHANGED] {doc.path.name}")
            else:
                synced += 1

        if synced > 0 and pending == 0 and changed == 0:
            click.echo(f"  All {synced} documents synced")
        else:
            click.echo(f"\n  Synced: {synced}, Pending: {pending}, Changed: {changed}")
        click.echo("")
    else:
        click.echo("=== Page Sync: Disabled ===")
        click.echo("")

    # Database sync status
    if config.database_sync.enabled:
        click.echo("=== Database Sync (Sprint Status) ===")

        try:
            epics, stories = scanner.scan_sprint_status()

            epics_synced = 0
            epics_pending = 0
            epics_changed = 0

            for epic in epics:
                state = store.get_db_state(epic.key)
                if state is None:
                    epics_pending += 1
                elif epic.mtime and state.last_synced_mtime != epic.mtime:
                    epics_changed += 1
                else:
                    epics_synced += 1

            stories_synced = 0
            stories_pending = 0
            stories_changed = 0

            for story in stories:
                state = store.get_db_state(story.key)
                if state is None:
                    stories_pending += 1
                elif story.content_hash and state.content_hash != story.content_hash:
                    stories_changed += 1
                elif story.mtime and state.last_synced_mtime != story.mtime:
                    stories_changed += 1
                else:
                    stories_synced += 1

            click.echo(
                f"  Epics:   Synced: {epics_synced}, "
                f"Pending: {epics_pending}, Changed: {epics_changed}"
            )
            click.echo(
                f"  Stories: Synced: {stories_synced}, "
                f"Pending: {stories_pending}, Changed: {stories_changed}"
            )

            all_synced = (
                epics_pending == 0
                and epics_changed == 0
                and stories_pending == 0
                and stories_changed == 0
            )
            if all_synced:
                click.echo("\n  All items up to date")

        except SprintStatusNotFoundError:
            click.echo("  No sprint-status.yaml found")

        click.echo("")
    else:
        click.echo("=== Database Sync: Disabled ===")
        click.echo("")


@cli.group()
def config():
    """Manage configuration."""
    pass


@config.command("show")
def config_show():
    """Show current configuration."""

    project_root = get_project_root()

    try:
        config = load_config(project_root)
    except ConfigNotFoundError as e:
        click.echo(f"Error: {e}", err=True)
        raise SystemExit(1)

    click.echo(f"Project: {config.project}")
    click.echo(f"Config file: {project_root / '.bmadnotion.yaml'}")
    click.echo("")

    click.echo("Notion:")
    click.echo(f"  Token env: {config.notion.token_env}")
    click.echo(f"  Workspace page: {config.notion.workspace_page_id}")
    click.echo("")

    click.echo("Page Sync:")
    click.echo(f"  Enabled: {config.page_sync.enabled}")
    if config.page_sync.enabled:
        click.echo(f"  Parent page: {config.page_sync.parent_page_id}")
        click.echo(f"  Documents: {len(config.page_sync.documents)}")
        for doc in config.page_sync.documents:
            click.echo(f"    - {doc.path}: {doc.title}")
    click.echo("")

    click.echo("Database Sync:")
    click.echo(f"  Enabled: {config.database_sync.enabled}")
    if config.database_sync.enabled:
        click.echo(f"  Projects DB: {config.database_sync.projects.database_id}")
        click.echo(f"  Sprints DB: {config.database_sync.sprints.database_id}")
        click.echo(f"  Tasks DB: {config.database_sync.tasks.database_id}")


@config.command("set-db")
@click.option("--projects", help="Projects database ID")
@click.option("--sprints", help="Sprints database ID")
@click.option("--tasks", help="Tasks database ID")
@click.option("--create-project", is_flag=True, help="Create Project row in database")
@click.option("--yes", "-y", is_flag=True, help="Skip confirmation")
def config_set_db(
    projects: str | None,
    sprints: str | None,
    tasks: str | None,
    create_project: bool,
    yes: bool,
):
    """Configure database IDs for sync.

    If no IDs are provided, searches Notion for databases named
    "Projects", "Sprints", and "Tasks" and prompts for confirmation.

    Use --create-project to also create a Project row in the database.

    Examples:
        bmad config set-db                    # Auto-detect from Notion
        bmad config set-db --projects abc123  # Set specific ID
        bmad config set-db -y                 # Auto-detect, skip confirmation
        bmad config set-db -y --create-project  # Auto-detect and create project
    """
    import os
    import re

    import yaml

    project_root = get_project_root()
    config_path = project_root / ".bmadnotion.yaml"

    if not config_path.exists():
        click.echo("Error: .bmadnotion.yaml not found. Run 'bmad init' first.", err=True)
        raise SystemExit(1)

    # If any ID is provided manually, use those
    if projects or sprints or tasks:
        db_ids = {
            "projects": projects,
            "sprints": sprints,
            "tasks": tasks,
        }
    else:
        # Auto-detect from Notion
        token = os.environ.get("NOTION_TOKEN")
        if not token:
            # Try loading from config
            try:
                cfg = load_config(project_root)
                token = cfg.get_notion_token()
            except (ConfigNotFoundError, TokenNotFoundError):
                pass

        if not token:
            click.echo("Error: NOTION_TOKEN not set. Export it or add to .env", err=True)
            raise SystemExit(1)

        if NotionClient is None:
            click.echo("Error: marknotion is not installed.", err=True)
            raise SystemExit(1)

        click.echo("Searching for databases in Notion...")
        client = NotionClient(token=token, on_retry=None)

        db_ids = {}
        for db_name in ["Projects", "Sprints", "Tasks"]:
            results = client.search(db_name, object_type="database")
            # Find exact match by title
            for result in results:
                title_parts = result.get("title", [])
                title = "".join(t.get("plain_text", "") for t in title_parts)
                if title.lower() == db_name.lower():
                    # Extract ID from URL (workaround for notion-client ID bug)
                    url = result.get("url", "")
                    match = re.search(r"([a-f0-9]{32})", url, re.IGNORECASE)
                    if match:
                        h = match.group(1).lower()
                        formatted_id = f"{h[:8]}-{h[8:12]}-{h[12:16]}-{h[16:20]}-{h[20:]}"
                        db_ids[db_name.lower()] = formatted_id
                    break

        # Show results
        click.echo("")
        click.echo("Found databases:")
        for name in ["projects", "sprints", "tasks"]:
            db_id = db_ids.get(name)
            status = db_id if db_id else click.style("Not found", fg="yellow")
            click.echo(f"  {name.capitalize()}: {status}")

        if not any(db_ids.values()):
            click.echo("")
            click.echo("No databases found. Make sure your integration has access to them.")
            raise SystemExit(1)

        # Confirm
        if not yes:
            click.echo("")
            if not click.confirm("Update .bmadnotion.yaml with these IDs?"):
                click.echo("Aborted.")
                return

    # Update config file
    with open(config_path) as f:
        config_content = yaml.safe_load(f)

    if "database_sync" not in config_content:
        config_content["database_sync"] = {"enabled": True}

    db_sync = config_content["database_sync"]

    if db_ids.get("projects"):
        if "projects" not in db_sync:
            db_sync["projects"] = {}
        db_sync["projects"]["database_id"] = db_ids["projects"]

    if db_ids.get("sprints"):
        if "sprints" not in db_sync:
            db_sync["sprints"] = {}
        db_sync["sprints"]["database_id"] = db_ids["sprints"]

    if db_ids.get("tasks"):
        if "tasks" not in db_sync:
            db_sync["tasks"] = {}
        db_sync["tasks"]["database_id"] = db_ids["tasks"]

    with open(config_path, "w") as f:
        yaml.dump(config_content, f, default_flow_style=False, sort_keys=False, allow_unicode=True)

    click.echo("")
    click.echo(f"Updated {config_path}")

    # Create project if requested
    if create_project and db_ids.get("projects"):
        click.echo("")
        click.echo("Creating Project row...")

        # Need token for API call
        token = os.environ.get("NOTION_TOKEN")
        if not token:
            try:
                cfg = load_config(project_root)
                token = cfg.get_notion_token()
            except (ConfigNotFoundError, TokenNotFoundError):
                click.echo("Error: NOTION_TOKEN not available for project creation", err=True)
                raise SystemExit(1)

        # Reload config to get project name
        cfg = load_config(project_root)
        project_name = cfg.project

        # Create project row using notion-client
        notion_client = Client(auth=token)
        try:
            page = notion_client.pages.create(
                parent={"database_id": db_ids["projects"]},
                properties={
                    "Project name": {"title": [{"text": {"content": project_name}}]},
                    "BMADProject": {"rich_text": [{"text": {"content": project_name}}]},
                },
            )
            click.echo(f"Created Project: {project_name} (ID: {page['id']})")
        except Exception as e:
            click.echo(f"Warning: Could not create project: {e}", err=True)
            click.echo("You may need to run 'bmad setup-db' first to add BMADProject field.")

    click.echo("")
    click.echo("Next steps:")
    if not create_project:
        click.echo("  1. Run 'bmad setup-db' to add sync key fields")
        click.echo("  2. Run 'bmad sync' to sync your project")
    else:
        click.echo("  1. Run 'bmad sync' to sync your project")


@cli.command("setup-db")
def setup_db():
    """Set up required fields in Notion databases.

    Adds sync key fields (BMADProject, BMADEpic, BMADStory) to the configured
    databases if they don't already exist.
    """
    from bmadnotion.schema import setup_all_databases

    project_root = get_project_root()

    # Load configuration
    try:
        config = load_config(project_root)
    except ConfigNotFoundError as e:
        click.echo(f"Error: {e}", err=True)
        raise SystemExit(1)

    # Check if database sync is enabled
    if not config.database_sync.enabled:
        click.echo("Database sync is disabled in configuration.")
        return

    # Get Notion token
    try:
        token = config.get_notion_token()
    except TokenNotFoundError as e:
        click.echo(f"Error: {e}", err=True)
        raise SystemExit(1)

    click.echo("Setting up database fields...")

    # Create Notion client
    client = Client(auth=token)

    try:
        results = setup_all_databases(client, config)

        if not results:
            click.echo("All required fields already exist.")
        else:
            for db_type, fields in results.items():
                click.echo(f"  Added to {db_type}: {', '.join(fields)}")

        click.echo("Done.")
    except Exception as e:
        click.echo(f"Error: {e}", err=True)
        raise SystemExit(1)


if __name__ == "__main__":
    cli()
