"""
Script to augment CloudFormation JSON schema with Markdown documentation.
"""

import argparse
import json
import re
import sys
from pathlib import Path


def log(s: str) -> None:
    print(s, file=sys.stderr)


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument(
        "--schema",
        help="CloudFormation JSON schema",
        type=Path,
        required=True,
    )
    parser.add_argument(
        "--docs",
        help="CloudFormation documentation (as generated by parse_docs.py)",
        type=Path,
        required=True,
    )
    args = parser.parse_args()

    schema = json.loads(args.schema.read_text())
    docs = json.loads(args.docs.read_text())["properties"]

    # Assumes schema is from GoFormation and has consistent structure
    # TODO: Use a more generic walk
    for def_name, def_schema in schema["definitions"].items():
        if not re.match(r"^\w+::\w+::\w+(.\w+)?$", def_name):
            log(f"Skipping {def_name}: not expected format")
            continue
        # If e.g. AWS::S3::Bucket, we only look under Properties
        # TODO: Support resource attributes et al.
        props = def_schema["properties"] if "." in def_name else def_schema["properties"]["Properties"]["properties"]
        page = def_name.replace(".", " ")
        if page not in docs:
            log(f"Skipping {def_name}: {page} not in docs")
            continue
        for prop_name, prop_schema in props.items():
            if prop_name not in docs[page]:
                log(f"Skipping {def_name}: {prop_name} not in {page} docs")
                continue
            prop_schema["markdownDescription"] = docs[page][prop_name]
            # GoFormation schema doesn't include it, so VS Code defaults to something unrelated (e.g. "Resources")
            prop_schema["title"] = prop_name

    print(
        json.dumps(
            schema,
            indent=2,
            sort_keys=True,
        )
    )


if __name__ == "__main__":
    main()
