# Copyright The OpenTelemetry Authors
# SPDX-License-Identifier: Apache-2.0

import os
import sys
from pathlib import Path

EXPECTED_LINES = (
    "# Copyright The OpenTelemetry Authors\n",
    "# SPDX-License-Identifier: Apache-2.0\n",
)

SKIP_SUFFIXES = (
    "_pb2.py",
    "_pb2_grpc.py",
)

SKIP_DIRS = (
    "target",
    ".tox",
    ".venv",
    "__pycache__",
    "node_modules",
)

GENERATED_MARKERS = (
    "# generated by datamodel-codegen",
    "# Generated by the protocol buffer compiler",
    "# Generated by the gRPC Python protocol compiler",
)


def should_skip(relpath):
    parts = relpath.split(os.sep)
    if any(d in parts for d in SKIP_DIRS):
        return True
    basename = os.path.basename(relpath)
    return any(basename.endswith(s) for s in SKIP_SUFFIXES)


def check_file(path):
    with open(path) as f:
        lines = f.readlines()

    # Skip empty files (e.g. namespace __init__.py)
    if not lines or all(line.strip() == "" for line in lines):
        return True

    # Skip generated files
    if any(lines[0].startswith(m) for m in GENERATED_MARKERS):
        return True

    # If file starts with a shebang, check lines after it
    start = 0
    if lines[0].startswith("#!"):
        start = 1
        # Skip optional blank line after shebang
        if start < len(lines) and lines[start].strip() == "":
            start += 1

    if len(lines) < start + 2:
        return False

    return (
        lines[start] == EXPECTED_LINES[0]
        and lines[start + 1] == EXPECTED_LINES[1]
    )


def main():
    root = str(Path(__file__).resolve().parents[1])
    failures = []

    for dirpath, dirnames, filenames in os.walk(root):
        dirnames[:] = [d for d in dirnames if not d.startswith(".")]

        for filename in filenames:
            if not filename.endswith(".py"):
                continue
            path = os.path.join(dirpath, filename)
            relpath = os.path.relpath(path, root)
            if should_skip(relpath):
                continue
            if not check_file(path):
                failures.append(relpath)

    if failures:
        print("Files missing the SPDX license header:")
        print()
        print("  Expected first two lines:")
        print("    # Copyright The OpenTelemetry Authors")
        print("    # SPDX-License-Identifier: Apache-2.0")
        print()
        for f in sorted(failures):
            print(f"  {f}")
        sys.exit(1)

    print("All files have the correct license header.")


if __name__ == "__main__":
    main()
