#!/usr/bin/env python3
"""Generate CODEOWNERS."""
import os
import sys

from manifest_helper import iter_manifests

BASE = """
# This file is generated by script/manifest/codeowners.py
# People marked here will be automatically requested for a review
# when the code that they own is touched.
# https://github.com/blog/2392-introducing-code-owners

# Home Assistant Core
setup.py @home-assistant/core
homeassistant/*.py @home-assistant/core
homeassistant/helpers/* @home-assistant/core
homeassistant/util/* @home-assistant/core

# Virtualization
Dockerfile @home-assistant/docker
virtualization/Docker/* @home-assistant/docker

# Other code
homeassistant/scripts/check_config.py @kellerza

# Integrations
"""

INDIVIDUAL_FILES = """
# Individual files
homeassistant/components/group/cover @cdce8p
homeassistant/components/demo/weather @fabaff
"""


def generate():
    """Generate CODEOWNERS."""
    parts = [BASE.strip()]

    for manifest in iter_manifests():
        if not manifest['codeowners']:
            continue

        parts.append("homeassistant/components/{}/* {}".format(
            manifest['domain'], ' '.join(manifest['codeowners'])))

    parts.append('\n' + INDIVIDUAL_FILES.strip())

    return '\n'.join(parts)


def main(validate):
    """Runner for CODEOWNERS gen."""
    if not os.path.isfile('requirements_all.txt'):
        print('Run this from HA root dir')
        return 1

    content = generate()

    if validate:
        with open('CODEOWNERS', 'r') as fp:
            if fp.read().strip() != content:
                print("CODEOWNERS is not up to date. "
                      "Run python script/manifest/codeowners.py")
                return 1
            return 0

    with open('CODEOWNERS', 'w') as fp:
        fp.write(content + '\n')


if __name__ == '__main__':
    sys.exit(main(sys.argv[-1] == 'validate'))