import os
import requests
import sys
import re

def get_expected_statuses(domain: str, parts: list[str], redirected_domains: set[str]) -> list[int]:
    """
    Determine the expected HTTP status codes based on the domain name.

    Args:
        domain: The full domain string (e.g. 'example.com').
        parts: The domain split into its subcomponents (e.g. ['www', 'example', 'com']).
        redirected_domains: A set of domains that should trigger a redirect.

    Returns:
        A list of expected HTTP status codes.
    """
    if domain == '{{domains | get_domain('web-app-listmonk')}}':
        return [404]
    if (parts and parts[0] == 'www') or (domain in redirected_domains):
        return [301]
    if domain == '{{domains | get_domain('web-app-yourls')}}':
        return [{{ applications | get_app_conf('web-app-yourls', 'server.status_codes.landingpage', True) }}]
    return [200, 302, 301]

# file in which fqdn server configs are deposit
config_path = '{{ NGINX.DIRECTORIES.HTTP.SERVERS }}'

# Initialize the error counter
error_counter = 0

# Regex pattern to match domain.tld or *.domain.tld
pattern = re.compile(r"^(?:[\w-]+\.)*[\w-]+\.[\w-]+\.conf$")

# Iterate over each file in the configuration directory
for filename in os.listdir(config_path):
    if filename.endswith('.conf') and pattern.match(filename):
        # Extract the domain and subdomain from the filename
        domain = filename.replace('.conf', '')
        parts = domain.split('.')
        
        # Prepare the URL and expected status codes
        url = f"{{ WEB_PROTOCOL }}://{domain}"
        
        redirected_domains = [domain['source'] for domain in {{ redirect_domain_mappings }}]
        redirected_domains.append("{{domains | get_domain('web-app-mailu')}}")

        expected_statuses = get_expected_statuses(domain, parts, redirected_domains)

        try:
            # Send a HEAD request to get only the response header
            response = requests.head(url)

            # Check if the status code matches the expected statuses
            if response.status_code in expected_statuses:
                print(f"{domain}: OK")
            else:
                print(f"{domain}: ERROR: Expected {expected_statuses}. Got {response.status_code}.")
                error_counter += 1
        except requests.RequestException as e:
            # Handle exceptions for requests like connection errors
            print(f"{domain}: error due to {e}")
            error_counter += 1

if error_counter > 0:
    print(f"Warning: {error_counter} domains responded with an unexpected https status code.")

# Exit the script with the number of errors as the exit code
sys.exit(error_counter)
