#!/usr/bin/env python3
# -----------------------------------------------------------------------------------------------------------
# Copyright (c) 2026 Huawei Technologies Co., Ltd.
# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
# CANN Open Software License Agreement Version 2.0 (the "License").
# Please refer to the License for details. You may not use this file except in compliance with the License.
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
# See LICENSE in the root of the software repository for the full text of the License.
# -----------------------------------------------------------------------------------------------------------

"""Collect incremental paths, run OAT and summarize the configured blocking checks."""
import importlib.util
import logging
import os
from pathlib import Path
import re
import shutil
import subprocess
import sys
from datetime import datetime, timezone

BLOCKING_HEADERS = ("Invalid File Type Total Count:", "License Header Invalid Total Count:")
SECTION_HEADER = re.compile(r"^[A-Za-z][A-Za-z .()/-]* Total Count:")
COUNT = re.compile(r"^(Invalid File Type Total Count:|License Header Invalid Total Count:)\s*(\d+)\s*$")
LOGGER = logging.getLogger("oat_check")


def configure_logging():
    formatter = logging.Formatter("[OAT] %(message)s")
    progress = logging.StreamHandler(sys.stdout)
    progress.addFilter(lambda record: record.levelno < logging.ERROR)
    errors = logging.StreamHandler(sys.stderr)
    errors.setLevel(logging.ERROR)
    for handler in (progress, errors):
        handler.setFormatter(formatter)
        LOGGER.addHandler(handler)
    LOGGER.setLevel(logging.INFO)
    LOGGER.propagate = False


def git_executable():
    executable = shutil.which("git")
    if executable is None:
        raise RuntimeError("Git executable was not found")
    return os.path.abspath(executable)


def repository_root(explicit_files):
    environment = dict(os.environ, LC_ALL="C")
    result = subprocess.run([git_executable(), "rev-parse", "--show-toplevel"],
                            stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=environment)
    if result.returncode:
        if explicit_files and b"not a git repository" in result.stderr:
            return Path.cwd()
        result.check_returncode()
    return Path(os.fsdecode(result.stdout.rstrip(b"\r\n")))


def collect_files(root, arguments):
    if arguments:
        names = [os.path.abspath(name) for name in arguments]
    else:
        result = subprocess.run(
            [git_executable(), "diff", "--cached", "--name-only", "-z", "--diff-filter=ACM"],
            cwd=str(root), stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=True)
        names = [os.fsdecode(name) for name in result.stdout.split(b"\0") if name]
    files = []
    for name in names:
        path = Path(name)
        absolute = os.path.abspath(str(path if path.is_absolute() else root / path))
        if not Path(absolute).is_file():
            raise ValueError("Cannot scan selected file: " + repr(name))
        if "," in absolute:
            raise ValueError("OAT's comma-separated file interface cannot represent: " + repr(name))
        if absolute not in files:
            files.append(absolute)
    return files


def ensure_oat():
    if importlib.util.find_spec("oat") is None:
        LOGGER.info("Installing oat-py>=1.0.1 ...")
        subprocess.run([sys.executable, "-m", "pip", "install", "--quiet", "oat-py>=1.0.1"], check=True)
        if importlib.util.find_spec("oat") is None:
            raise RuntimeError("oat-py is unavailable after installation")


def report_sections(report):
    sections, counts = {}, {}
    active = None
    for line in report.splitlines():
        if not SECTION_HEADER.match(line):
            if active:
                sections[active].append(line)
            continue
        active = None
        match = COUNT.match(line)
        if not match:
            continue
        active = match.group(1)
        if active in counts:
            raise ValueError("Duplicate OAT report section: " + active)
        counts[active] = int(match.group(2))
        sections[active] = [line]
    if set(counts) != set(BLOCKING_HEADERS):
        raise ValueError("OAT report is missing a required blocking check")
    return counts, sections


def run_check(root, files):
    ensure_oat()
    directory = root / "oat_reports"
    directory.mkdir(exist_ok=True)
    report_file = directory / ("PlainReport_" + root.name + ".txt")
    summary_file = directory / "result.txt"
    # A previous invocation's report must never determine this invocation's result.
    for previous in (report_file, summary_file):
        if previous.exists():
            previous.unlink()
    command = [sys.executable, "-m", "oat", "-mode", "s", "-s", str(root),
               "-r", str(directory), "-n", root.name, "-w", "1", "-f", ",".join(files)]
    config = root / "OAT.xml"
    if config.is_file():
        command += ["-oatconfig", str(config)]
    LOGGER.info("Checking %d file(s)...", len(files))
    with (directory / "scan.log").open("wb") as log:
        result = subprocess.run(command, cwd=str(root), stdout=log, stderr=subprocess.STDOUT)
    if result.returncode not in (0, 1):
        raise RuntimeError("OAT exited with code {}; see {}".format(result.returncode, directory / "scan.log"))
    if not report_file.is_file():
        raise RuntimeError("OAT did not produce its report; see " + str(directory / "scan.log"))
    counts, sections = report_sections(report_file.read_text(encoding="utf-8-sig"))
    output = ["OAT Scan Result Summary", "Scan Time: " + datetime.now(timezone.utc).isoformat(timespec="seconds"),
              "Project: " + root.name, "Files Checked: " + str(len(files))]
    for marker in BLOCKING_HEADERS:
        output += ["", *sections[marker]]
    summary_file.write_text("\n".join(output).rstrip() + "\n", encoding="utf-8")
    issues = sum(counts.values())
    LOGGER.info("%s. Summary: %s", "Commit blocked: {} issue(s)".format(issues)
                if issues else "All checks passed", summary_file)
    return 1 if issues else 0


def main(arguments):
    try:
        root = repository_root(bool(arguments))
        files = collect_files(root, arguments)
        if not files:
            LOGGER.info("No staged files to check. Skipping.")
            return 0
        return run_check(root, files)
    except (OSError, subprocess.CalledProcessError, ValueError, RuntimeError) as error:
        detail = str(error)
        if isinstance(error, subprocess.CalledProcessError) and error.stderr:
            detail += "\n" + os.fsdecode(error.stderr).strip()
        LOGGER.error("Check failed: %s", detail)
        return 2


if __name__ == "__main__":
    configure_logging()
    sys.exit(main(sys.argv[1:]))