"""
DDNS (Dynamic DNS) implementation for the DecentraBrowser system.
"""
import os
import json
from datetime import datetime
from .constants import DEFAULT_DDNS_FILE
from .utils import load_json_file, save_json_file, is_valid_domain_format, is_valid_ipv4

class DDNS:
    """Dynamic DNS manager for resolving domain names to IP addresses."""
    
    def __init__(self, ddns_file=DEFAULT_DDNS_FILE):
        """Initialize the DDNS manager with a file path."""
        self.ddns_file = ddns_file
        self.entries = {}
        self.load()
    
    def load(self):
        """Load DDNS entries from file."""
        self.entries = load_json_file(self.ddns_file, default={})
        
    def save(self):
        """Save DDNS entries to file."""
        save_json_file(self.ddns_file, self.entries)
    
    def add_entry(self, domain, ip, port):
        """Add or update a DDNS entry."""
        if not is_valid_domain_format(domain):
            return False, "Invalid domain format"
        
        if not is_valid_ipv4(ip):
            return False, "Invalid IP address"
        
        try:
            port = int(port)
            if port < 1 or port > 65535:
                return False, "Port must be between 1 and 65535"
        except ValueError:
            return False, "Port must be a number"
        
        self.entries[domain] = {
            'ip': ip,
            'port': port,
            'updated': datetime.utcnow().isoformat()
        }
        
        self.save()
        
        # Try to register with central server
        self.register_with_central(domain, ip, port)
        return True, "Entry added successfully"
    
    def register_with_central(self, domain, ip, port, title=None):
        
        try:
            import requests
            
            # Build registration URL
            register_url = f"http://jcmc.serveminecraft.net/cent.php?register={domain}&ip={ip}&port={port}"
            if title:
                register_url += f"&title={title}"
            
            # Send request
            response = requests.get(register_url, timeout=15)
            
            if response.status_code == 200:
                try:
                    data = response.json()
                    if data.get('success'):
                        return True, "Domain registered with central server"
                    else:
                        return False, data.get('error', 'Registration failed')
                except:
                    if "success" in response.text.lower():
                        return True, "Domain registered with central server"
                    else:
                        return False, f"Registration failed: {response.text}"
            else:
                return False, f"HTTP error: {response.status_code}"
        except Exception as e:
            return False, f"Error: {str(e)}"
    
    def check_availability_central(self, domain):
        
        try:
            import requests
            
            # Build check URL
            check_url = f"http://jcmc.serveminecraft.net/cent.php?check={domain}"
            
            # Send request
            response = requests.get(check_url, timeout=10)
            
            if response.status_code == 200:
                try:
                    data = response.json()
                    if data.get('available') is True:
                        return True, "Domain is available"
                    else:
                        return False, data.get('reason', 'Domain is not available')
                except:
                    if "available" in response.text.lower():
                        return True, "Domain is available"
                    else:
                        return False, "Domain is not available"
            else:
                return False, f"HTTP error: {response.status_code}"
        except Exception as e:
            return False, f"Error: {str(e)}"

    def remove_entry(self, domain):
        """Remove a DDNS entry."""
        if domain in self.entries:
            del self.entries[domain]
            self.save()
        
        # Try to unregister with central server
            self.unregister_with_central(domain)
        return True, "Entry removed successfully"
        return False, "Domain not found"
    
    def unregister_with_central(self, domain):
        
        try:
            import requests
            
            # Build unregistration URL
            unregister_url = f"http://jcmc.serveminecraft.net/cent.php?unregister={domain}"
            
            # Send request
            response = requests.get(unregister_url, timeout=15)
            
            if response.status_code == 200:
                try:
                    data = response.json()
                    if data.get('success'):
                        return True, "Domain unregistered from central server"
                    else:
                        return False, data.get('error', 'Unregistration failed')
                except:
                    if "success" in response.text.lower():
                        return True, "Domain unregistered from central server"
                    else:
                        return False, f"Unregistration failed: {response.text}"
            else:
                return False, f"HTTP error: {response.status_code}"
        except Exception as e:
            return False, f"Error: {str(e)}"
    
    def resolve(self, domain):
        """Resolve a domain to its IP and port."""
        entry = self.entries.get(domain)
        if not entry:
            return None, None
        
        return entry['ip'], entry['port']
    
    def list_entries(self):
        """List all DDNS entries."""
        return {domain: entry for domain, entry in self.entries.items()}
    
    def has_domain(self, domain):
        """Check if a domain exists in the DDNS file."""
        return domain in self.entries
    
    def update_from_registry(self, domains):
        """Update DDNS entries from a list of Domain objects."""
        updated = 0
        for domain in domains:
            if domain.ip and domain.port:
                result, _ = self.add_entry(domain.full_name, domain.ip, domain.port)
                if result:
                    updated += 1
        
        return updated