#!/usr/bin/env python3

# https://developers.home-assistant.io/docs/creating_integration_manifest#zeroconf

import os
import json
import sys
from collections import defaultdict

if __name__ == "__main__":
    if len(sys.argv) < 3:
        print(
            "Usage: ./get_homeassistant_discovery_data.py </path/to/homeassistant-repo/homeassistant> <output_directory>"
        )
        sys.exit(1)

    parent_dir = sys.argv[1]
    output_directory = sys.argv[2]

    brand_data = {}
    for root, dirs, files in os.walk(f"{parent_dir}/brands"):
        for file in files:
            if file.endswith(".json"):
                file_path = os.path.join(root, file)
                with open(file_path, "r") as f:
                    manifest = json.load(f)
                    filename = os.path.basename(os.path.dirname(file_path))
                    brand_domain = manifest.get("domain")
                    brand_name = manifest.get("name")
                    brand_data[brand_name.casefold()] = {
                        "display_name": brand_name,
                        "source": "homeassistant_brands",
                    }
    with open(f"{output_directory}/ha_brands.json", "w") as f:
        json.dump(brand_data, f, indent=4)

    ssdp_data = []
    mqtt_data = defaultdict(list)
    dhcp_data = []
    homekit_data = defaultdict(list)
    integration_data = {}
    integrations = 0
    for root, dirs, files in os.walk(f"{parent_dir}/components"):
        for file in files:
            if file == "manifest.json":
                file_path = os.path.join(root, file)
                with open(file_path, "r") as f:
                    manifest = json.load(f)
                    filename = os.path.basename(os.path.dirname(file_path))
                    integration_domain = manifest.get("domain")
                    integration_name = manifest.get("name")
                    if (
                        "zeroconf" in manifest.keys()
                        or "ssdp" in manifest.keys()
                        or "homekit" in manifest.keys()
                        or "mqtt" in manifest.keys()
                        or "dhcp" in manifest.keys()
                    ):
                        integrations += 1
                    for key, value in manifest.items():
                        integration_data[integration_domain] = {
                            "name": integration_name
                        }

                        # commented out as I have manually changed the schema
                        # if key == "zeroconf":
                        #     for service in value:
                        #         if isinstance(service, str):
                        #             merged_data["zeroconf"][service].append(
                        #                 {
                        #                     "integration_domain": integration_domain,
                        #                     "integration_name": integration_name,
                        #                 }
                        #             )
                        #         elif isinstance(service, dict):
                        #             merged_data["zeroconf"][service["type"]].append(
                        #                 {
                        #                     "integration_domain": integration_domain,
                        #                     "integration_name": integration_name,
                        #                     "match_device_name": service.get("name"),
                        #                     "match_properties": service.get(
                        #                         "properties"
                        #                     ),
                        #                 }
                        #             )
                        if key == "ssdp":
                            # TODO: instead of organizing one key per filename, make the data structure a big long array/dict, with the name of the supported integration as a value
                            for ssdp_criteria in value:
                                ssdp_data.append(
                                    {
                                        "search": ssdp_criteria,
                                        "integration": integration_domain,
                                    }
                                )
                        elif key == "mqtt":
                            for service in value:
                                mqtt_data[service] = integration_domain
                        elif key == "dhcp":
                            for dhcp_criteria in value:
                                # I don't think the registered_devices bit is relevant to us
                                if not dhcp_criteria.get("registered_devices"):
                                    dhcp_data.append(
                                        {
                                            "search": dhcp_criteria,
                                            "integration": integration_domain,
                                        }
                                    )
                        elif key == "homekit":
                            for model in value["models"]:
                                homekit_data[model] = integration_domain

        json.dump(
            integration_data,
            open(f"{output_directory}/ha_integrations.json", "w"),
            indent=4,
        )
        json.dump(ssdp_data, open(f"{output_directory}/ssdp.json", "w"), indent=4)
        json.dump(homekit_data, open(f"{output_directory}/homekit.json", "w"), indent=4)
        json.dump(mqtt_data, open(f"{output_directory}/mqtt.json", "w"), indent=4)
        json.dump(dhcp_data, open(f"{output_directory}/dhcp.json", "w"), indent=4)
