"""
Cloudflare CLI commands
Manage Cloudflare DNS records
"""

import sys
import json
from ..core.cloudflare import CloudflareManager


def cf_list_domains():
    """List all Cloudflare domains"""
    cf = CloudflareManager()

    if not cf.api_token:
        print("✗ Cloudflare API token not configured")
        print("Set it with: infra cloudflare configure")
        sys.exit(1)

    print("\nYour Cloudflare Domains:")
    print("-" * 60)

    zones = cf.list_zones()
    if not zones:
        print("No domains found")
        return

    for i, zone in enumerate(zones, 1):
        print(f"{i}. {zone['name']} ({zone['id']})")


def cf_list_records(domain: str):
    """List DNS records for a domain"""
    cf = CloudflareManager()

    if not cf.api_token:
        print("✗ Cloudflare API token not configured")
        sys.exit(1)

    zone = cf.get_zone_by_name(domain)
    if not zone:
        print(f"✗ Domain '{domain}' not found")
        sys.exit(1)

    print(f"\nDNS Records for {domain}:")
    print("-" * 60)
    print(f"{'Type':<10} {'Name':<30} {'Content':<30} {'Proxied':<10}")
    print("-" * 60)

    records = cf.list_dns_records(zone["id"])
    for record in records:
        print(f"{record['type']:<10} {record['name']:<30} {record['content']:<30} {str(record['proxied']):<10}")


def cf_add_record(domain: str, record_type: str, name: str, content: str, proxied: bool = True):
    """Add a DNS record"""
    cf = CloudflareManager()

    if not cf.api_token:
        print("✗ Cloudflare API token not configured")
        sys.exit(1)

    zone = cf.get_zone_by_name(domain)
    if not zone:
        print(f"✗ Domain '{domain}' not found")
        sys.exit(1)

    full_name = f"{name}.{domain}" if name != "@" else domain

    print(f"Adding DNS record: {full_name} -> {content}")

    result = cf.add_dns_record(zone["id"], record_type, full_name, content, proxied=proxied)

    if result.get("success"):
        print(f"✓ DNS record created successfully")
        print(f"  Record ID: {result['result']['id']}")
    else:
        print(f"✗ Failed to create DNS record")
        print(json.dumps(result, indent=2))
        sys.exit(1)


def cf_test():
    """Test Cloudflare connection"""
    cf = CloudflareManager()

    if not cf.api_token:
        print("✗ Cloudflare API token not configured")
        sys.exit(1)

    print("Testing Cloudflare connection...")

    result = cf.test_connection()
    if result["success"]:
        print("✓ Connection successful")
        data = result["data"].get("result", {})
        if data:
            status = data.get("status", "Unknown")
            print(f"  Token status: {status}")
    else:
        print("✗ Connection failed")
        if "error" in result:
            print(f"  Error: {result['error']}")
        sys.exit(1)


def cf_list_tokens():
    """List all named Cloudflare tokens"""
    from ..core.config import Config

    tokens = Config.get_cloudflare_tokens()

    print("\nNamed Cloudflare Tokens:")
    print("-" * 60)

    if not tokens:
        print("No tokens found. Add one with: infra cloudflare add-token <name>")
        return

    for name, token_info in tokens.items():
        print(f"  {name}:")
        print(f"    Email: {token_info.get('email', 'N/A')}")
        # Mask the token for security
        token = token_info.get('token', '')
        if token:
            masked = token[:8] + "..." + token[-4:]
            print(f"    Token: {masked}")


def cf_add_token_interactive(name: str):
    """Interactive helper to add a token"""
    print(f"\nAdding Cloudflare token: {name}")
    print("-" * 60)

    print("\nYou need a Cloudflare API Token with Zone:DNS and Zone:Zone permissions.")
    print("Create one at: https://dash.cloudflare.com/profile/api-tokens\n")

    api_token = input("Enter your Cloudflare API Token: ").strip()
    email = input("Enter your email (for Let's Encrypt): ").strip()

    from ..core.config import Config

    if api_token:
        if Config.add_cloudflare_token(name, api_token, email):
            print(f"\n✓ Token '{name}' added successfully")
        else:
            print(f"\n✗ Failed to add token")
    else:
        print("\n✗ Token is required")


def cf_add_token(name: str):
    """Add a named Cloudflare token"""
    cf_add_token_interactive(name)


def cf_remove_token(name: str):
    """Remove a named Cloudflare token"""
    from ..core.config import Config

    tokens = Config.get_cloudflare_tokens()

    if name not in tokens:
        print(f"✗ Token '{name}' not found")
        sys.exit(1)

    print(f"\nRemoving Cloudflare token: {name}")
    confirm = input("Are you sure? (yes/no): ").strip().lower()

    if confirm == "yes":
        if Config.remove_cloudflare_token(name):
            print(f"✓ Token '{name}' removed successfully")
        else:
            print(f"✗ Failed to remove token")
    else:
        print("Cancelled")


def cf_test_token(name: str):
    """Test a specific Cloudflare token"""
    cf = CloudflareManager(token_name=name)

    print(f"\nTesting Cloudflare token: {name}")
    print("-" * 60)

    result = cf.test_connection()
    if result["success"]:
        print("✓ Connection successful")
        data = result["data"].get("result", {})
        if data:
            status = data.get("status", "Unknown")
            print(f"  Token status: {status}")

        # Show accessible domains
        zones = cf.list_zones()
        print(f"  Accessible zones: {len(zones)}")
        for zone in zones:
            print(f"    - {zone['name']}")
    else:
        print("✗ Connection failed")
        if "error" in result:
            print(f"  Error: {result['error']}")
        sys.exit(1)


def cf_set_service_token(service: str, token_name: str):
    """Set which Cloudflare token a service should use"""
    from ..core.config import Config

    # Validate service
    if not Config.service_exists(service):
        print(f"✗ Service '{service}' not found")
        print(f"Available services: {', '.join(Config.SERVICES)}")
        sys.exit(1)

    # Validate token
    tokens = Config.get_cloudflare_tokens()
    if token_name not in tokens:
        print(f"✗ Token '{token_name}' not found")
        print(f"Available tokens: {', '.join(tokens.keys())}")
        sys.exit(1)

    # Get current service config
    service_config = Config.get_service_config(service) or {}
    service_config["cloudflare_token"] = token_name

    # Save service config
    if Config.set_service_config(service, service_config):
        print(f"✓ Service '{service}' will now use token '{token_name}'")
    else:
        print(f"✗ Failed to update service configuration")


def cf_configure():
    """Configure Cloudflare credentials (DEPRECATED - use add-token)"""
    print("\n⚠️  This method is deprecated. Use: infra cloudflare add-token <name>")
    cf_add_token_interactive("default")
