#!/usr/bin/env python3
"""License compliance analysis script for ekfsm project"""
import json
import yaml
import sys
from pathlib import Path
from datetime import datetime


def load_license_policy():
    """Load license policy configuration"""
    policy_file = Path(".license-policy.yaml")
    if not policy_file.exists():
        print("⚠️  No .license-policy.yaml found, using default policy", file=sys.stderr)
        return {
            "permitted_licenses": [
                "MIT",
                "MIT License",
                "BSD",
                "BSD License",
                "Apache-2.0",
                "Apache Software License",
                "ISC",
            ],
            "review_required": [
                "GPL",
                "LGPL",
                "MPL-2.0",
                "LGPL-2.1-or-later",
                "GNU Lesser General Public License",
            ],
            "prohibited_licenses": ["AGPL-1.0"],
            "package_exceptions": {},
            "compliance_settings": {
                "fail_on_prohibited": True,
                "warn_on_review_required": True,
                "fail_on_unknown": False,
                "require_license_files": True,
            },
        }

    try:
        with open(policy_file, "r") as f:
            return yaml.safe_load(f)
    except Exception as e:
        print(f"❌ Error loading license policy: {e}", file=sys.stderr)
        return None


def analyze_licenses():
    """Analyze licenses against policy"""
    try:
        policy = load_license_policy()
        if not policy:
            return 1

        with open("license-report.json", "r") as f:
            licenses = json.load(f)

        total_packages = len(licenses)
        permitted_count = 0
        review_required_count = 0
        prohibited_count = 0
        unknown_count = 0

        compliance_report = {
            "scan_timestamp": datetime.now().isoformat(),
            "total_packages": total_packages,
            "license_breakdown": {},
            "compliance_summary": {},
            "potential_issues": [],
            "policy_violations": [],
        }

        exit_code = 0

        for pkg in licenses:
            pkg_name = pkg["Name"]
            license_name = pkg.get("License", "Unknown").strip()

            # Check for package-specific overrides
            if pkg_name in policy.get("package_exceptions", {}):
                license_name = policy["package_exceptions"][pkg_name]

            # Count licenses
            if license_name in compliance_report["license_breakdown"]:
                compliance_report["license_breakdown"][license_name] += 1
            else:
                compliance_report["license_breakdown"][license_name] = 1

            # Categorize license
            is_permitted = any(
                perm in license_name for perm in policy.get("permitted_licenses", [])
            )
            is_review_required = any(
                rev in license_name for rev in policy.get("review_required", [])
            )
            is_prohibited = any(
                pro in license_name for pro in policy.get("prohibited_licenses", [])
            )
            is_unknown = (
                license_name in ["Unknown", "UNKNOWN"] or not license_name.strip()
            )

            if is_prohibited:
                prohibited_count += 1
                compliance_report["policy_violations"].append(
                    {
                        "package": pkg_name,
                        "version": pkg["Version"],
                        "license": license_name,
                        "violation_type": "PROHIBITED",
                        "severity": "HIGH",
                    }
                )
                if policy.get("compliance_settings", {}).get(
                    "fail_on_prohibited", True
                ):
                    exit_code = 1

            elif is_review_required:
                review_required_count += 1
                compliance_report["potential_issues"].append(
                    {
                        "package": pkg_name,
                        "version": pkg["Version"],
                        "license": license_name,
                        "issue": "Copyleft license - requires legal review",
                    }
                )
                if policy.get("compliance_settings", {}).get(
                    "warn_on_review_required", True
                ):
                    print(f"⚠️  {pkg_name}: {license_name} requires review")

            elif is_unknown:
                unknown_count += 1
                compliance_report["potential_issues"].append(
                    {
                        "package": pkg_name,
                        "version": pkg["Version"],
                        "license": license_name,
                        "issue": "Unknown license - manual review required",
                    }
                )
                if policy.get("compliance_settings", {}).get("fail_on_unknown", False):
                    exit_code = 1

            elif is_permitted:
                permitted_count += 1
            else:
                # License not explicitly categorized
                compliance_report["potential_issues"].append(
                    {
                        "package": pkg_name,
                        "version": pkg["Version"],
                        "license": license_name,
                        "issue": "License not in policy - requires review",
                    }
                )

        risk_level = (
            "HIGH"
            if (prohibited_count > 0)
            else (
                "MEDIUM" if (review_required_count > 0 or unknown_count > 0) else "LOW"
            )
        )

        compliance_report["compliance_summary"] = {
            "permitted_licenses": permitted_count,
            "review_required_licenses": review_required_count,
            "prohibited_licenses": prohibited_count,
            "unknown_licenses": unknown_count,
            "risk_level": risk_level,
            "policy_compliant": len(compliance_report["policy_violations"]) == 0,
        }

        with open("license-compliance-report.json", "w") as f:
            json.dump(compliance_report, f, indent=2)

        # Print summary to console
        print("📊 License Compliance Summary:")
        print(f"  Total packages: {total_packages}")
        print(f"  Permitted licenses: {permitted_count}")
        print(f"  Require review: {review_required_count}")
        print(f"  Prohibited licenses: {prohibited_count}")
        print(f"  Unknown licenses: {unknown_count}")
        print(f"  Risk level: {risk_level}")

        if compliance_report["policy_violations"]:
            print(
                f'❌ Found {len(compliance_report["policy_violations"])} policy violations'
            )
            for violation in compliance_report["policy_violations"]:
                print(
                    f'   - {violation["package"]} ({violation["license"]}) - {violation["violation_type"]}'
                )

        if (
            compliance_report["potential_issues"]
            and not compliance_report["policy_violations"]
        ):
            print(
                f'⚠️  Found {len(compliance_report["potential_issues"])} items requiring review'
            )

        if exit_code == 0 and not compliance_report["potential_issues"]:
            print("✅ All licenses compliant with policy")

        return exit_code

    except Exception as e:
        print(f"❌ Error analyzing licenses: {e}", file=sys.stderr)
        return 1


if __name__ == "__main__":
    exit_code = analyze_licenses()
    sys.exit(exit_code)
