"""Compares a `wp plugin check --format=csv` report with ci/plugin-check-baseline.txt.

Prints the errors that are not in the baseline and exits 1 when there are any. Each occurrence counts:
a file/code pair listed twice in the baseline allows two such errors, a third one is new. Writes every
current error to <out> ("file<TAB>code", one line per occurrence) so the baseline can be updated from it.
Usage: plugin-check-compare.py <report.csv> <baseline.txt> <out.txt>
"""
import csv
import sys
from collections import Counter

report, baseline_path, out_path = sys.argv[1:4]

errors = Counter()
current_file = None
with open(report, encoding="utf-8") as handle:
    for line in handle:
        line = line.rstrip("\n")
        if line.startswith("FILE: "):
            current_file = line[len("FILE: "):].strip()
            continue
        if not current_file or not line or line.startswith("line,"):
            continue
        row = next(csv.reader([line]))
        if len(row) >= 4 and row[2] == "ERROR":
            errors[f"{current_file}\t{row[3]}"] += 1

with open(out_path, "w", encoding="utf-8") as handle:
    handle.write("".join(f"{error}\n" for error in sorted(errors.elements())))

with open(baseline_path, encoding="utf-8") as handle:
    baseline = Counter(line.rstrip("\n") for line in handle if line.strip() and not line.startswith("#"))

new = sorted((errors - baseline).elements())
fixed = sorted((baseline - errors).elements())
total = sum(errors.values())
print(f"Plugin Check: {total} errors, {total - len(new)} known (ci/plugin-check-baseline.txt), {len(new)} new.")
if fixed:
    print(f"{len(fixed)} baseline entries no longer occur; remove them from the baseline.")
for error in new:
    print(f"NEW  {error}")
sys.exit(1 if new else 0)
