#!/usr/bin/python3
import argparse
import yaml
from jinja2 import Template


def render_template(template_path, **kwargs):
    with open(template_path, "r") as file:
        template = Template(file.read())
        output = template.render(**kwargs)
    return output


def format_subdomain(subdomains, domain):
    if isinstance(subdomains, list):
        return ", ".join([f"{sub}.{domain}" for sub in subdomains])
    else:
        return f"{subdomains}.{domain}"


def process_sites_config(config_path, template_path, check_mode):
    with open(config_path, "r") as file:
        sites_config = yaml.safe_load(file)

    default_domain = sites_config.get("default_domain", None)
    if default_domain is None:
        raise ValueError("YAML configuration is missing default_domain key")
    total_sites = len(sites_config["sites"])
    enabled_sites = 0
    disabled_sites = 0

    for site in sites_config["sites"]:
        domain = site.get("domain", default_domain)
        # Check if site is enabled
        if site.get("enabled", True):  # Default to True if 'enabled' key is not present
            enabled_sites += 1

            if "subdomain" in site:
                site["subdomain"] = format_subdomain(site["subdomain"], domain)

            if not check_mode:
                rendered_content = render_template(template_path, **site)
                print(f"{rendered_content}\n")
        else:
            disabled_sites += 1

    if check_mode:
        print(f"Total sites: {total_sites}")
        print(f"Enabled sites: {enabled_sites}")
        print(f"Disabled sites: {disabled_sites}")


def main():
    parser = argparse.ArgumentParser(
        description="Process a sites configuration file for Caddyfiles"
    )
    parser.add_argument(
        "--config", required=True, help="Path to the YAML configuration file"
    )
    parser.add_argument(
        "--check",
        action="store_true",
        help="Only check statistics, do not output templates",
    )
    parser.add_argument("--template", help="Path to the Jinja2 template file")
    args = parser.parse_args()

    if args.template is None and args.check is False:
        parser.error("--template argument is required if not using --check")

    template_path = args.template  # Replace with the actual path to your template file
    process_sites_config(args.config, template_path, args.check)


if __name__ == "__main__":
    main()