"""Inert local tests. Prints results; never fetches, submits, or runs payloads.

Requires yara-python, pysigma, and PyYAML. Sigma predicate evaluation below is
a deliberately small local reference matcher, NOT a SIEM/backend execution.
Snort checks below exercise intent only, NOT Snort parsing or packet handling.
"""
import hashlib
import importlib.metadata
import json
from pathlib import Path
import re

import yara
import yaml
from sigma.collection import SigmaCollection

ROOT = Path(__file__).resolve().parent
fixtures = json.loads((ROOT / "fixtures.json").read_text(encoding="utf-8"))
supplemental = json.loads((ROOT / "supplemental-fixtures.json").read_text(encoding="utf-8"))
fixtures.update({k: v for k, v in supplemental.items() if isinstance(v, list)})
checks = []


def checked(name, actual, expected, tier):
    assert actual == expected, f"{name}: got {actual!r}, expected {expected!r}"
    checks.append({"name": name, "tier": tier, "status": "PASS"})


def selection_matches(selection, event):
    for field_modifier, expected in selection.items():
        field, modifier = field_modifier.split("|")
        value = event.get(field)
        if not isinstance(value, str):
            return False
        if modifier == "contains":
            result = expected.casefold() in value.casefold()
        elif modifier == "re":
            result = re.search(expected, value) is not None
        else:
            raise ValueError(f"Unsupported local reference modifier: {modifier}")
        if not result:
            return False
    return True


for filename, fixture_group, selections, connective in [
    ("sigma-web-php2shell-label.yml", "web", ["selection"], "and"),
    ("sigma-linux-php-worker-child.yml", "process", ["selection_parent", "selection_child"], "and"),
    ("sigma-web-libredtail-user-agent.yml", "libredtail", ["selection"], "and"),
    ("sigma-linux-loader-pipe-vector.yml", "loader_pipeline", ["selection_pipeline", "selection_scp"], "or"),
    ("sigma-linux-apache-child.yml", "apache", ["selection_parent", "selection_child"], "and"),
]:
    source = (ROOT / filename).read_text(encoding="utf-8")
    parsed = SigmaCollection.from_yaml(source)
    checked(filename + " pySigma parse", len(parsed.rules), 1, "SIGMA_PARSE")
    rule = yaml.safe_load(source)
    checked(filename + " condition", rule["detection"]["condition"],
            (" " + connective + " ").join(selections), "LOCAL_PREDICATE")
    for case in fixtures[fixture_group]:
        selected = [selection_matches(rule["detection"][s], case["event"])
                    for s in selections]
        match = any(selected) if connective == "or" else all(selected)
        checked(filename + ": " + case["name"], match, case["match"], "LOCAL_PREDICATE")

rules = yara.compile(filepath=str(ROOT / "php2shell-offline-triage.yar"), error_on_warning=True)
checks.append({"name": "YARA compile without warnings", "tier": "YARA_ENGINE", "status": "PASS"})
for case in fixtures["text"]:
    actual = sorted(m.rule for m in rules.match(data=case["text"].encode("utf-8")))
    checked(case["name"], actual, sorted(case["rules"]), "YARA_ENGINE")

filler_rule = ["DC_Known_Repetitive_Upload_Artifact"]
for name, data, digest in [
    ("filler a", b"\r\n" + b"A" * 5184 + b"B" * 5184,
     "150ae88f0999032e2a6113501d6082f54a3ed98d02427b21a96e773a27d7bf16"),
    ("filler b", b"C" * 64,
     "27d926a6708d6769d97d065e7a5a860ab496eab272c03d1cebc55ec71b954fa2"),
]:
    checked(name + " reconstructed SHA256", hashlib.sha256(data).hexdigest(), digest, "BYTE_HASH")
    checked(name + " exact YARA correlation", [m.rule for m in rules.match(data=data)], filler_rule, "YARA_ENGINE")
    changed = data[:-1] + b"D"
    checked(name + " one-byte mutation", [m.rule for m in rules.match(data=changed)], [], "YARA_ENGINE")

checked("generic repeated filler", [m.rule for m in rules.match(data=b"A" * 100)], [], "YARA_ENGINE")
checked("over 2 MiB text guard", [m.rule for m in rules.match(data=b"php2shell" + b"X" * (2 * 1024 * 1024))], [], "YARA_ENGINE")

for case in fixtures["http_body"]:
    # Checks the intended same-buffer predicate. Does not emulate Snort's HTTP
    # normalization, TCP reassembly, inspector depth, or PCRE implementation.
    body = case["body"]
    actual = ("multipart/form-data" in case["content_type"].lower()
              and "PHP_SESSION_UPLOAD_PROGRESS" in body
              and "<?php" in body.lower()
              and re.search(r"\b(system|shell_exec|passthru)\s*\(", body, re.I) is not None)
    checked("Snort intent: " + case["name"], actual, case["match"], "LOCAL_PREDICATE_ONLY")

# Read simple predicates from the shipped files. These tests do not emulate
# platform parsers, time scoping, CIM extraction, endpoint event collection,
# network direction/outcome mapping, source selectors, or deduplication.
network_kql = (ROOT / "defender-shared-loader-network.kql").read_text(encoding="utf-8")
network_spl = (ROOT / "splunk-shared-loader-outbound.spl").read_text(encoding="utf-8")
kql_ip = re.search(r'RemoteIP == "([0-9.]+)"', network_kql).group(1)
spl_active = re.sub(r"```.*?```", " ", network_spl, flags=re.S)
spl_ip = re.search(r'dest_ip="([0-9.]+)"', spl_active).group(1)
checked("Splunk default has no direction filter", "direction=" in spl_active, False, "STATIC_EXTRACTION")
spl_direction = re.search(r'```\| search direction="([a-z]+)"```', network_spl).group(1)
for case in fixtures["network"]:
    event = case["event"]
    checked("Defender network predicate: " + case["name"],
            event.get("RemoteIP") == kql_ip, case["defender_match"], "LOCAL_PREDICATE_ONLY")
    checked("Splunk default destination predicate: " + case["name"],
            event.get("dest_ip") == spl_ip,
            case["splunk_match"], "LOCAL_PREDICATE_ONLY")
    checked("Splunk optional outbound predicate: " + case["name"],
            event.get("dest_ip") == spl_ip and event.get("direction") == spl_direction,
            case["splunk_outbound_match"], "LOCAL_PREDICATE_ONLY")

errors_spl = (ROOT / "splunk-php-worker-errors.spl").read_text(encoding="utf-8")
error_patterns = re.findall(r'match\(_raw,"([^"]+)"\),"([^"]+)"', errors_spl)
checked("Splunk error-family pattern count", len(error_patterns), 6, "STATIC_EXTRACTION")
for case in fixtures["errors"]:
    family = next((label for pattern, label in error_patterns
                   if re.search(pattern, case["text"])), None)
    checked("Splunk error predicate: " + case["name"], family, case["family"], "LOCAL_PREDICATE_ONLY")

report = {
    "versions": {"yara-python": yara.__version__, "pysigma": importlib.metadata.version("pysigma"),
                 "PyYAML": yaml.__version__},
    "checks": checks,
    "not_performed": ["Sigma backend conversion/deployment", "Snort 3 compilation/PCAP replay",
                      "Defender KQL tenant execution", "Splunk SPL tenant execution",
                      "Falcon LogScale tenant execution", "Sumo Logic tenant execution"],
}
print(json.dumps(report, indent=2))
