# testss.py
import subprocess
import json
import sys

def scan_with_bandit(target_file):
    try:
        cmd = [sys.executable, "-m", "bandit", "-f", "json", "--quiet", target_file]
        result = subprocess.run(cmd, capture_output=True, text=True, timeout=60)

        if result.stderr:
            print("Bandit 日志信息:", result.stderr)

        try:
            report = json.loads(result.stdout)
        except json.JSONDecodeError as e:
            print(f"JSON 解析失败: {e}")
            print("stdout 内容:", result.stdout)
            return None

        return report

    except subprocess.TimeoutExpired:
        print("Bandit 扫描超时")
        return None
    except FileNotFoundError:
        print("未找到 bandit 模块，请执行：")
        print(f"{sys.executable} -m pip install bandit")
        return None

if __name__ == "__main__":
    target = "cyanlove_import_layer_tosqlite.py"
    report = scan_with_bandit(target)

    if report:
        issues = report.get("results", [])
        if issues:
            print(f"\n发现 {len(issues)} 个安全问题：")
            for idx, issue in enumerate(issues, 1):
                severity = issue.get('issue_severity', 'UNKNOWN')
                confidence = issue.get('issue_confidence', 'UNKNOWN')
                line = issue.get('line_number', '?')
                text = issue.get('issue_text', '无描述')
                more_info = issue.get('more_info') or issue.get('issue_url', '')
                fname = issue.get('fname', '')
                print(f"\n{idx}. [{severity.upper()}] 行 {line}: {text}")
                if more_info:
                    print(f"   详情: {more_info}")
                if fname:
                    print(f"   文件: {fname}")
        else:
            print("\n未发现安全问题！")

        # ===== 修正统计信息解析 =====
        metrics = report.get("metrics", {})
        # 注意：Bandit 的 JSON 中，metrics 下有两个子对象：_totals 和 _scored
        totals = metrics.get("_totals", {})
        # 或者可能直接是 metrics 下的 "totals"，但安全起见用 _totals
        severity_counts = totals.get("SEVERITY", {})
        confidence_counts = totals.get("CONFIDENCE", {})

        print("\n扫描统计：")
        print(f"总代码行数: {totals.get('loc', 0)}")
        print(f"高危问题: {severity_counts.get('HIGH', 0)}")
        print(f"中危问题: {severity_counts.get('MEDIUM', 0)}")
        print(f"低危问题: {severity_counts.get('LOW', 0)}")
        print(f"可信度：高 {confidence_counts.get('HIGH', 0)}，中 {confidence_counts.get('MEDIUM', 0)}，低 {confidence_counts.get('LOW', 0)}")
    else:
        print("扫描失败，无法获取报告")