"""SARIF output for GitHub Actions integration.

Generates SARIF v2.1.0 JSON that GitHub can display as inline PR annotations.
Usage in CI:
  sdkspindle check --format sarif *.kt > results.sarif
  Then upload with actions/upload-sarif@v2
"""

from typing import List

SARIF_VERSION = "2.1.0"
SARIF_SCHEMA = "https://json.schemastore.org/sarif-2.1.0.json"

RULE_DESCRIPTIONS = {
    "OPTIONAL_NO_CALL": {
        "name": "OptionalBareAccess",
        "short": "Bare property access on Optional<T> field",
        "full": "Fields returning Optional<T> in the Google GenAI Java SDK must be accessed via method call with .orElse() unwrapping. Bare property access (Kotlin-style) will fail at runtime.",
        "help": "Use `.fieldName().orElse(defaultValue)` instead of `.fieldName`",
    },
    "WRONG_TYPE": {
        "name": "WrongParameterType",
        "short": "Wrong argument type for builder method",
        "full": "Builder methods in the GenAI SDK have strict parameter types. Common mistake: passing String where Duration or Instant is expected.",
        "help": "Use `Duration.ofDays(7)` instead of `\"604800s\"`, or `Instant.parse(...)` instead of a string.",
    },
    "MISSING_ARGS": {
        "name": "MissingArguments",
        "short": "Service method called with insufficient arguments",
        "full": "Service methods (caches.list, caches.create, etc.) require specific parameters. Calling with empty parens will fail.",
        "help": "Check the method signature and provide all required parameters.",
    },
    "UNKNOWN_TYPE": {
        "name": "UnknownSDKType",
        "short": "Import references non-existent SDK type",
        "full": "The imported class does not exist in the current SDK version. This may indicate a typo or version mismatch.",
        "help": "Check the class name spelling and verify your SDK version.",
    },
    "MISSING_IMPORT": {
        "name": "MissingImport",
        "short": "SDK type used but not imported",
        "full": "A type from com.google.genai.types is used in code but not imported.",
        "help": "Add the missing import statement.",
    },
    "LISTOF_VARARGS": {
        "name": "UnnecessaryListOf",
        "short": "listOf() wrapper on varargs method",
        "full": "The builder method accepts varargs, so wrapping in listOf() is unnecessary.",
        "help": "Pass elements directly: `.contents(elem1, elem2)` instead of `.contents(listOf(elem1, elem2))`",
    },
    "STRING_ENUM": {
        "name": "StringInsteadOfEnum",
        "short": "String literal where Known enum expected",
        "full": "The builder method expects a Known enum value, not a string.",
        "help": "Use `TypeName.Known.VALUE` instead of a string literal.",
    },
}


def to_sarif(issues: list) -> dict:
    """Convert list of Issue to SARIF v2.1.0 JSON."""
    rules = []
    rule_indices = {}
    results = []

    for issue in issues:
        # Register rule if not seen
        if issue.code not in rule_indices:
            rule_indices[issue.code] = len(rules)
            desc = RULE_DESCRIPTIONS.get(issue.code, {})
            rules.append({
                "id": issue.code,
                "name": desc.get("name", issue.code),
                "shortDescription": {"text": desc.get("short", issue.code)},
                "fullDescription": {"text": desc.get("full", issue.message)},
                "helpUri": "https://github.com/elb-pr/sdkspindle",
                "help": {"text": desc.get("help", "See sdkspindle documentation.")},
                "defaultConfiguration": {
                    "level": "error" if issue.severity == "ERROR" else "warning"
                },
            })

        # Create result
        result = {
            "ruleId": issue.code,
            "ruleIndex": rule_indices[issue.code],
            "level": "error" if issue.severity == "ERROR" else "warning",
            "message": {"text": issue.message},
            "locations": [{
                "physicalLocation": {
                    "artifactLocation": {"uri": issue.file},
                    "region": {
                        "startLine": max(1, issue.line),
                        "startColumn": 1,
                    }
                }
            }],
        }
        results.append(result)

    return {
        "$schema": SARIF_SCHEMA,
        "version": SARIF_VERSION,
        "runs": [{
            "tool": {
                "driver": {
                    "name": "sdkspindle",
                    "informationUri": "https://github.com/elb-pr/sdkspindle",
                    "version": "0.1.0",
                    "rules": rules,
                }
            },
            "results": results,
        }],
    }
