# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import sys
import subprocess
from pathlib import Path

from .logger import info, cmd as log_cmd


def run_scancode(scan_target: Path, result_json: Path, jobs: int = 8, scan_license: bool = False):
    """
    Run ScanCode Toolkit.
    
    直接调用 scancode 命令进行扫描。
    
    Args:
        scan_target: 要扫描的目标路径
        result_json: 输出JSON文件路径
        jobs: 并行任务数
        scan_license: 是否扫描license信息
    """
    cmd = [
        "scancode",
        "-c",  # 扫描copyright
        "--only-findings",
        "--json-pp",
        str(result_json),
        str(scan_target),
        "-n",
        str(jobs),
    ]
    
    # 添加license扫描参数
    if scan_license:
        cmd.insert(1, "-l")  # 扫描license

    info("Running scancode:")
    log_cmd(" ".join(cmd))

    result = subprocess.run(
        cmd,
        stdout=sys.stdout,
        stderr=sys.stderr,
    )

    if result.returncode != 0:
        raise RuntimeError(f"ScanCode failed with exit code {result.returncode}")