#!/usr/bin/env python3

import json
import os
import sys


def build_local_settings(input_path: str) -> dict:
    with open(input_path, "r", encoding="utf-8") as f:
        data = json.load(f)

    if not isinstance(data, list):
        raise ValueError(
            "Input JSON must be a top-level array of app setting objects.")

    values = {}

    for i, item in enumerate(data):
        if not isinstance(item, dict):
            raise ValueError(f"Item at index {i} is not a JSON object.")

        name: str = item.get("name")
        value = item.get("value")

        if not name:
            raise ValueError(f"Item at index {
                             i} is missing a non-empty 'name' field.")

        if name.lower() == "apim_url":
            # APIM_URL should be blank for local runs
            value = ""

        # Azure local.settings.json expects string values under Values
        if value is None:
            value = ""

        values[name] = str(value)

    return {
        "IsEncrypted": False,
        "Values": values
    }


def main():
    if len(sys.argv) != 2:
        print("Usage: python convert_appsettings.py <input_json_file>")
        sys.exit(1)

    input_path = sys.argv[1]

    if not os.path.isfile(input_path):
        print(f"Error: file not found: {input_path}")
        sys.exit(1)

    try:
        local_settings = build_local_settings(input_path)
    except Exception as e:
        print(f"Error: {e}")
        sys.exit(1)

    output_path = os.path.join(os.getcwd(), "local.settings.json")

    with open(output_path, "w", encoding="utf-8") as f:
        json.dump(local_settings, f, indent=2)

    print(f"Wrote {output_path}")


if __name__ == "__main__":
    main()
