import click


def register_cli_commands(app):
    @app.cli.command("seed-data")
    @click.option("--sample", is_flag=True, help="Include sample companies, users, and tickets.")
    def seed_data_command(sample: bool):
        from app.services.bootstrap_service import BootstrapService

        BootstrapService.seed_defaults(with_sample_data=sample)
        click.echo("Seed data created.")

    @app.cli.command("export-schema")
    def export_schema_command():
        from scripts.export_mysql_schema import export_schema

        export_schema()
        click.echo("MySQL schema exported.")

    @app.cli.command("send-test-email")
    @click.option("--to", "recipient", help="Recipient email address. Defaults to MAIL_FROM_ADDRESS.")
    @click.option("--subject", default="KHF SMP SMTP Test", help="Email subject.")
    def send_test_email_command(recipient: str | None, subject: str):
        from app.services.email_service import EmailService
        from app.services.settings_service import SettingsService

        config = SettingsService.mail_config()
        target = recipient or config["from_address"]
        if not target:
            raise click.ClickException("Recipient email is required because MAIL_FROM_ADDRESS is empty.")

        body = "\n".join(
            [
                "This is a live SMTP test from KHF SMP.",
                f"SMTP host: {config['host'] or '(not configured)'}",
                f"TLS enabled: {config['use_tls']}",
                "",
                "If you received this message, live email delivery is working.",
            ]
        )
        if not EmailService.send_email([target], subject, body):
            raise click.ClickException("Email was not sent. Check SMTP configuration and application logs.")
        click.echo(f"Email sent successfully to {target}.")

    @app.cli.command("send-test-telegram")
    @click.option("--chat-id", required=True, help="Telegram chat ID or channel username.")
    @click.option("--message", default="KHF SMP Telegram test message", help="Message text.")
    def send_test_telegram_command(chat_id: str, message: str):
        from app.services.telegram_service import TelegramService

        if not TelegramService.send_message(chat_id, message):
            raise click.ClickException("Telegram message was not sent. Check the bot token, chat ID, and application logs.")
        click.echo(f"Telegram message sent successfully to {chat_id}.")

    @app.cli.command("telegram-updates")
    @click.option("--limit", default=20, help="Number of recent updates to fetch.")
    def telegram_updates_command(limit: int):
        from app.services.telegram_service import TelegramService

        updates = TelegramService.get_updates(limit=limit)
        if not updates:
            click.echo("No Telegram updates returned.")
            return
        for update in updates:
            message = update.get("message") or {}
            chat = message.get("chat") or {}
            sender = message.get("from") or {}
            text = message.get("text", "")
            click.echo(
                " | ".join(
                    [
                        f"update_id={update.get('update_id')}",
                        f"chat_id={chat.get('id')}",
                        f"chat_type={chat.get('type')}",
                        f"user={sender.get('username') or sender.get('first_name') or 'unknown'}",
                        f"text={text}",
                    ]
                )
            )

    @app.cli.command("telegram-sync-updates")
    @click.option("--limit", default=50, help="Maximum number of pending Telegram updates to process.")
    def telegram_sync_updates_command(limit: int):
        from app.services.telegram_service import TelegramService

        result = TelegramService.process_pending_updates(limit=limit)
        click.echo(
            f"Processed {result['count']} Telegram update(s). Last update id: {result['last_update_id']}."
        )

    @app.cli.command("telegram-set-webhook")
    @click.option("--base-url", required=True, help="Public HTTPS base URL, e.g. https://example.com")
    def telegram_set_webhook_command(base_url: str):
        from app.services.telegram_service import TelegramService

        target = base_url.rstrip("/") + "/api/v1/integrations/telegram/webhook"
        if not TelegramService.set_webhook(target):
            raise click.ClickException("Telegram webhook was not set. Check the bot token, username, and logs.")
        click.echo(f"Telegram webhook set to {target}.")

    @app.cli.command("apply-user-security-update")
    def apply_user_security_update_command():
        from scripts.apply_user_security_update import main

        exit_code = main()
        if exit_code:
            raise click.ClickException("The user security update did not complete successfully.")

    @app.cli.command("namecheap-preflight")
    def namecheap_preflight_command():
        from scripts.namecheap_preflight import run_preflight

        exit_code = run_preflight()
        if exit_code:
            raise click.ClickException("Namecheap preflight reported warnings or errors.")
