#!/usr/bin/env python3
"""
GoDaddy DNS Setup via API
Uses GoDaddy API to add DNS records for sunaivadigital.com
"""

import requests
import json

# Configuration
DOMAIN = "sunaivadigital.com"

# DNS Records to add
DNS_RECORDS = [
    {
        "type": "A",
        "name": "api",
        "data": "152.53.201.221",
        "ttl": 600
    },
    {
        "type": "CNAME",
        "name": "www",
        "data": "sunaiva-talking-widget.netlify.app",
        "ttl": 3600
    }
]

def setup_dns_via_api(api_key, api_secret):
    """
    Add DNS records via GoDaddy API

    Args:
        api_key: GoDaddy API Key
        api_secret: GoDaddy API Secret
    """

    headers = {
        "Authorization": f"sso-key {api_key}:{api_secret}",
        "Content-Type": "application/json"
    }

    base_url = "https://api.godaddy.com/v1/domains"

    print("=" * 80)
    print("GoDaddy DNS Setup via API")
    print("=" * 80)
    print(f"\nDomain: {DOMAIN}")
    print(f"\nRecords to add:")
    for record in DNS_RECORDS:
        print(f"  - {record['type']}: {record['name']} -> {record['data']} (TTL: {record['ttl']})")
    print("=" * 80)
    print()

    # First, get current DNS records to verify domain access
    print("Fetching current DNS records...")
    get_url = f"{base_url}/{DOMAIN}/records"

    try:
        response = requests.get(get_url, headers=headers)
        response.raise_for_status()
        current_records = response.json()
        print(f"✅ Successfully accessed domain - found {len(current_records)} existing records")

    except requests.exceptions.RequestException as e:
        print(f"❌ Error accessing domain: {str(e)}")
        if hasattr(e.response, 'text'):
            print(f"Response: {e.response.text}")
        return False

    # Add each DNS record
    success_count = 0
    for record in DNS_RECORDS:
        print(f"\nAdding {record['type']} record: {record['name']} -> {record['data']}")

        # PATCH request to add/update the specific record
        patch_url = f"{base_url}/{DOMAIN}/records/{record['type']}/{record['name']}"

        payload = [{
            "data": record['data'],
            "ttl": record['ttl']
        }]

        try:
            response = requests.put(patch_url, headers=headers, json=payload)
            response.raise_for_status()
            print(f"✅ {record['type']} record added successfully")
            success_count += 1

        except requests.exceptions.RequestException as e:
            print(f"❌ Error adding {record['type']} record: {str(e)}")
            if hasattr(e.response, 'text'):
                print(f"Response: {e.response.text}")
            continue

    print("\n" + "=" * 80)
    print(f"Results: {success_count}/{len(DNS_RECORDS)} records added successfully")
    print("=" * 80)

    if success_count == len(DNS_RECORDS):
        print("\n✅ All DNS records configured successfully!")
        print("\nNext steps:")
        print("1. Wait 5-10 minutes for DNS propagation")
        print("2. Test A record: dig api.sunaivadigital.com")
        print("3. Test CNAME: dig www.sunaivadigital.com")
        print("4. Verify at: https://dcc.godaddy.com/control/sunaivadigital.com/dns")
        return True
    else:
        print("\n⚠️ Some records failed to add - check errors above")
        return False

def get_api_instructions():
    """Print instructions for creating GoDaddy API keys"""

    print("\n" + "=" * 80)
    print("HOW TO CREATE GODADDY API KEYS")
    print("=" * 80)
    print("""
1. Go to: https://developer.godaddy.com/keys
2. Log in with your GoDaddy account (108866004 / TripleWebsites333)
3. Click "Create New API Key"
4. Choose:
   - Environment: Production (for real domains)
   - Name: Genesis DNS Management
5. Click "Create"
6. SAVE the API Key and Secret immediately (they won't be shown again)
7. Run this script with your keys:

   python scripts/godaddy_dns_api_setup.py <API_KEY> <API_SECRET>

Example:
   python scripts/godaddy_dns_api_setup.py dSvX3j_8xvXtFsAu7aHh dSvX3j_8xvXtFsAu7aHh_secret

SECURITY NOTE:
- Keep API keys secure - they have full access to your domains
- Never commit them to git
- Store in environment variables or secrets manager for production
""")
    print("=" * 80)

if __name__ == "__main__":
    import sys

    if len(sys.argv) != 3:
        print("❌ Missing API credentials")
        print("\nUsage: python godaddy_dns_api_setup.py <API_KEY> <API_SECRET>\n")
        get_api_instructions()
        sys.exit(1)

    api_key = sys.argv[1]
    api_secret = sys.argv[2]

    success = setup_dns_via_api(api_key, api_secret)

    sys.exit(0 if success else 1)
