import yaml
import requests
import re
import os

# Cloudflare API Konfiguration
CLOUDFLARE_API_TOKEN = os.getenv("CLOUDFLARE_API_TOKEN")
CLOUDFLARE_ZONE_ID = os.getenv("CLOUDFLARE_ZONE_ID")
CLOUDFLARE_API_URL = f"https://api.cloudflare.com/client/v4/zones/{CLOUDFLARE_ZONE_ID}/dns_records"

HEADERS = {
    "Authorization": f"Bearer {CLOUDFLARE_API_TOKEN}",
    "Content-Type": "application/json"
}

def load_domains(file_path="domains.yaml"):
    with open(file_path, "r") as file:
        return yaml.safe_load(file)

def is_reserved(domain, reserved_patterns):
    return any(re.match(pattern, domain) for pattern in reserved_patterns)

def get_existing_records():
    response = requests.get(CLOUDFLARE_API_URL, headers=HEADERS)
    if response.status_code == 200:
        return {rec["name"]: rec for rec in response.json().get("result", [])}
    return {}

def update_cloudflare():
    data = load_domains()
    reserved_patterns = data.get("reserved_domains", [])
    subdomains = data.get("subdomains", [])
    
    existing_records = get_existing_records()
    
    for subdomain in subdomains:
        full_domain = f"{subdomain['name']}.morlana.page"
        
        if is_reserved(full_domain, reserved_patterns):
            print(f"Skipping reserved domain: {full_domain}")
            continue
        
        record_data = {
            "type": "CNAME",
            "name": full_domain,
            "content": subdomain["target"],
            "proxied": subdomain.get("proxy", True)
        }
        
        if full_domain in existing_records:
            record_id = existing_records[full_domain]["id"]
            response = requests.put(f"{CLOUDFLARE_API_URL}/{record_id}", json=record_data, headers=HEADERS)
        else:
            response = requests.post(CLOUDFLARE_API_URL, json=record_data, headers=HEADERS)
        
        if response.status_code in [200, 201]:
            print(f"Successfully updated {full_domain}")
        else:
            print(f"Failed to update {full_domain}: {response.text}")

if __name__ == "__main__":
    update_cloudflare()
