"""CLI interface — Click commands that delegate to clawdflare.lib.tools.

Usage:
    clawdflare setup                   # interactive setup via popups
    clawdflare setup --account work    # setup a second account
    clawdflare accounts                # list configured accounts
    clawdflare use personal            # switch active account
    clawdflare zones                   # list zones
    clawdflare audit example.com       # audit against best practices
    clawdflare fix example.com --apply # fix settings (PIN required)
    clawdflare serve                   # start MCP server
"""

import asyncio
import json

import click

from clawdflare import __version__
from clawdflare.lib import tools


def _run(coro):
    """Run an async coroutine synchronously."""
    return asyncio.run(coro)


def _output(result: dict):
    """Pretty-print a tool result as JSON."""
    click.echo(json.dumps(result, indent=2))


@click.group()
@click.version_option(version=__version__, prog_name="clawdflare")
def main():
    """clawdflare — opinionated Cloudflare management CLI."""


# ---------------------------------------------------------------------------
# Account management
# ---------------------------------------------------------------------------

@main.command()
@click.option("--account", default=None, help="Account name (prompted via popup if omitted).")
def setup(account):
    """Set up a Cloudflare account via native OS popups.

    Collects account name, token names, read token, write token, and PIN
    through secure dialogs. The AI agent never sees any secrets.
    """
    from clawdflare.lib import vault

    try:
        result = vault.interactive_setup(account)
        click.echo(json.dumps(result, indent=2))
    except RuntimeError as e:
        click.echo(f"Setup failed: {e}", err=True)
        raise SystemExit(1)


@main.command()
def accounts():
    """List all configured Cloudflare accounts."""
    from clawdflare.lib import vault
    accts = vault.list_accounts()
    if not accts:
        click.echo("No accounts configured. Run `clawdflare setup`.")
        return
    _output(accts)


@main.command()
@click.argument("account")
def use(account):
    """Switch the active Cloudflare account."""
    from clawdflare.lib import vault
    try:
        vault.set_active_account(account)
        click.echo(f"Active account: {account}")
    except RuntimeError as e:
        click.echo(str(e), err=True)
        raise SystemExit(1)


# ---------------------------------------------------------------------------
# Read operations
# ---------------------------------------------------------------------------

@main.command()
def zones():
    """List all zones in the account."""
    _output(_run(tools.zones()))


@main.command("zone-settings")
@click.argument("zone")
def zone_settings(zone):
    """Get all settings for a zone."""
    _output(_run(tools.zone_settings(zone)))


@main.command("dns-records")
@click.argument("zone")
def dns_records(zone):
    """List DNS records for a zone."""
    _output(_run(tools.dns_records(zone)))


@main.command()
@click.argument("zone")
def audit(zone):
    """Audit a zone against opinionated best practices."""
    _output(_run(tools.audit(zone)))


@main.command("ssl-status")
@click.argument("zone")
def ssl_status(zone):
    """Get SSL/TLS configuration summary."""
    _output(_run(tools.ssl_status(zone)))


# ---------------------------------------------------------------------------
# Write operations (PIN-protected)
# ---------------------------------------------------------------------------

@main.command()
@click.argument("zone")
@click.option("--setting", default=None, help="Fix a single setting.")
@click.option("--dry-run/--apply", default=True, help="Preview changes (default) or apply them.")
def fix(zone, setting, dry_run):
    """Fix settings to match opinions."""
    _output(_run(tools.fix(zone, setting, dry_run)))


@main.command("purge-cache")
@click.argument("zone")
@click.option("--everything", is_flag=True, help="Purge all cached content.")
@click.option("--url", "urls", multiple=True, help="Specific URLs to purge.")
def purge_cache(zone, everything, urls):
    """Purge cached content."""
    _output(_run(tools.purge_cache(zone, everything, list(urls) or None)))


@main.command("set-setting")
@click.argument("zone")
@click.argument("setting")
@click.argument("value")
def set_setting(zone, setting, value):
    """Set a specific zone setting."""
    _output(_run(tools.set_setting(zone, setting, value)))


# ---------------------------------------------------------------------------
# MCP server
# ---------------------------------------------------------------------------

@main.command()
def serve():
    """Start the MCP server (for Claude Code, Cursor, etc.)."""
    from clawdflare.mcp import mcp
    mcp.run()
