#!/usr/bin/env python3
"""
DNS Verification Script
Checks if sunaivadigital.com DNS records are configured correctly
"""

import subprocess
import time

DOMAIN = "sunaivadigital.com"

EXPECTED_RECORDS = {
    "api": {
        "type": "A",
        "value": "152.53.201.221"
    },
    "www": {
        "type": "CNAME",
        "value": "sunaiva-talking-widget.netlify.app"
    }
}

def check_dns_record(subdomain, record_type):
    """Check a DNS record using dig or nslookup"""

    fqdn = f"{subdomain}.{DOMAIN}" if subdomain else DOMAIN

    # Try dig first (cleaner output)
    try:
        result = subprocess.run(
            ["dig", "+short", fqdn, record_type],
            capture_output=True,
            text=True,
            timeout=10
        )

        if result.returncode == 0:
            output = result.stdout.strip()
            return output if output else None
        else:
            return None

    except FileNotFoundError:
        # Fallback to nslookup if dig not available
        try:
            result = subprocess.run(
                ["nslookup", "-type=" + record_type, fqdn],
                capture_output=True,
                text=True,
                timeout=10
            )

            if result.returncode == 0:
                output = result.stdout
                # Parse nslookup output
                for line in output.split('\n'):
                    if record_type == "A" and "Address:" in line and "#" not in line:
                        return line.split("Address:")[-1].strip()
                    elif record_type == "CNAME" and "canonical name" in line.lower():
                        return line.split("=")[-1].strip()
                return None
            else:
                return None

        except FileNotFoundError:
            print("❌ Neither 'dig' nor 'nslookup' found - install dnsutils")
            return None

    except subprocess.TimeoutExpired:
        print(f"⚠️ Timeout checking {fqdn}")
        return None
    except Exception as e:
        print(f"❌ Error checking {fqdn}: {str(e)}")
        return None

def verify_all_records():
    """Verify all expected DNS records"""

    print("=" * 80)
    print("DNS Verification for sunaivadigital.com")
    print("=" * 80)
    print()

    all_passed = True

    for subdomain, expected in EXPECTED_RECORDS.items():
        fqdn = f"{subdomain}.{DOMAIN}"
        record_type = expected["type"]
        expected_value = expected["value"]

        print(f"Checking {record_type} record for {fqdn}...")

        actual_value = check_dns_record(subdomain, record_type)

        if actual_value is None:
            print(f"  ❌ No {record_type} record found")
            print(f"  Expected: {expected_value}")
            print(f"  Got: (none)")
            all_passed = False

        elif record_type == "CNAME":
            # CNAME often has trailing dot
            actual_clean = actual_value.rstrip('.')
            expected_clean = expected_value.rstrip('.')

            if actual_clean == expected_clean:
                print(f"  ✅ CORRECT: {actual_value}")
            else:
                print(f"  ❌ MISMATCH")
                print(f"  Expected: {expected_value}")
                print(f"  Got: {actual_value}")
                all_passed = False

        elif actual_value == expected_value:
            print(f"  ✅ CORRECT: {actual_value}")

        else:
            print(f"  ❌ MISMATCH")
            print(f"  Expected: {expected_value}")
            print(f"  Got: {actual_value}")
            all_passed = False

        print()

    print("=" * 80)

    if all_passed:
        print("✅ ALL DNS RECORDS CONFIGURED CORRECTLY!")
        print()
        print("Next steps:")
        print("1. Update Talking Widget config to use api.sunaivadigital.com")
        print("2. Configure SSL certificate on Elestio")
        print("3. Deploy backend with new domain")
        print("4. Test widget embed")
        return True
    else:
        print("⚠️ SOME DNS RECORDS ARE MISSING OR INCORRECT")
        print()
        print("Possible causes:")
        print("1. DNS records not yet added - add them at:")
        print("   https://dcc.godaddy.com/control/sunaivadigital.com/dns")
        print("2. DNS propagation in progress - wait 5-10 minutes and try again")
        print("3. Wrong values configured - double-check the records")
        print()
        print("Expected configuration:")
        for subdomain, expected in EXPECTED_RECORDS.items():
            fqdn = f"{subdomain}.{DOMAIN}"
            print(f"  {expected['type']:6} {fqdn:30} → {expected['value']}")
        return False

def continuous_check(interval=30, max_attempts=20):
    """Continuously check DNS until records are correct"""

    print(f"Continuous DNS monitoring - checking every {interval} seconds...")
    print(f"Maximum {max_attempts} attempts (~{max_attempts * interval // 60} minutes)")
    print()

    for attempt in range(1, max_attempts + 1):
        print(f"\n--- Attempt {attempt}/{max_attempts} ---")

        if verify_all_records():
            print(f"\n🎉 DNS records verified successfully on attempt {attempt}!")
            return True

        if attempt < max_attempts:
            print(f"\nWaiting {interval} seconds before next check...")
            time.sleep(interval)

    print("\n⏱️ Max attempts reached - DNS records still not correct")
    print("Manual intervention may be required")
    return False

if __name__ == "__main__":
    import sys

    if len(sys.argv) > 1 and sys.argv[1] == "--watch":
        # Continuous monitoring mode
        continuous_check()
    else:
        # Single check mode
        verify_all_records()
        print("\nTip: Use '--watch' flag to continuously monitor DNS propagation:")
        print("  python scripts/verify_dns_setup.py --watch")
