#!/usr/bin/env python3
"""diffside — side-by-side diff of two files in the terminal, with color.
Usage: diffside [--width N] [--no-color] [--context N] FILE1 FILE2
The two files next to each other, line by line: unchanged lines in both
columns, removed lines only on the left (red), added lines only on the right
(green), changed lines paired and highlighted — a merge-conflict-free way to
actually read what changed.
"""
import argparse, difflib, shutil, sys

RED = "\033[31m"
GREEN = "\033[32m"
YELLOW = "\033[33m"
RESET = "\033[0m"


def side_lines(a_lines, b_lines, width, color):
    sm = difflib.SequenceMatcher(a=a_lines, b=b_lines, autojunk=False)
    col = max(10, (width - 3) // 2)
    rows = []
    for tag, i1, i2, j1, j2 in sm.get_opcodes():
        if tag == "equal":
            for x, y in zip(a_lines[i1:i2], b_lines[j1:j2]):
                rows.append((" ", x.rstrip("\n"), y.rstrip("\n")))
        elif tag == "delete":
            for x in a_lines[i1:i2]:
                rows.append(("-", x.rstrip("\n"), ""))
        elif tag == "insert":
            for y in b_lines[j1:j2]:
                rows.append(("+", "", y.rstrip("\n")))
        else:
            pairs = list(zip(a_lines[i1:i2], b_lines[j1:j2]))
            for x, y in pairs:
                rows.append(("~", x.rstrip("\n"), y.rstrip("\n")))
            for x in a_lines[i1 + len(pairs):i2]:
                rows.append(("-", x.rstrip("\n"), ""))
            for y in b_lines[j1 + len(pairs):j2]:
                rows.append(("+", "", y.rstrip("\n")))
    out = []
    for tag, left, right in rows:
        l, r = left[:col], right[:col]
        code = {"-": RED, "+": GREEN, "~": YELLOW}.get(tag, "")
        if color and code:
            out.append(f"{code}{l:<{col}}{RESET} | {code}{r:<{col}}{RESET}")
        else:
            mark = {"-": "<", "+": ">", "~": "!", " ": " "}[tag]
            out.append(f"{mark} {l:<{col}} | {r:<{col}}")
    return out


def main(argv=None):
    ap = argparse.ArgumentParser(prog="diffside",
        description="Side-by-side diff of two files in the terminal, with color.")
    ap.add_argument("file1", help="first file")
    ap.add_argument("file2", help="second file")
    ap.add_argument("--width", type=int, default=0, help="total width (default: terminal width)")
    ap.add_argument("--no-color", action="store_true", help="disable colours, use < > ! markers")
    ap.add_argument("--selftest", action="store_true", help="run a built-in self-test and exit")
    argv_list = list(argv) if argv is not None else sys.argv[1:]
    if "--selftest" in argv_list:
        return selftest()
    a = ap.parse_args(argv)
    if a.selftest:
        return selftest()
    try:
        with open(a.file1, encoding="utf-8", errors="replace") as fh:
            a_lines = fh.readlines()
        with open(a.file2, encoding="utf-8", errors="replace") as fh:
            b_lines = fh.readlines()
    except OSError as e:
        print(f"diffside: {e}", file=sys.stderr)
        return 1
    width = a.width or shutil.get_terminal_size((120, 24)).columns
    color = not a.no_color and sys.stdout.isatty()
    rows = side_lines(a_lines, b_lines, width, color)
    n_diff = sum(1 for r in rows if r.startswith(("\033[31m", "\033[32m", "\033[33m", "<", ">", "!")))
    for row in rows:
        print(row)
    print(f"diffside: {len(a_lines)} vs {len(b_lines)} lines, {n_diff} differing row(s)",
          file=sys.stderr)
    return 0 if a_lines == b_lines else 1


def selftest():
    import tempfile, os
    a = ["one\n", "two\n", "three\n"]
    b = ["one\n", "TWO\n", "three\n", "four\n"]
    rows = side_lines(a, b, 80, False)
    joined = "\n".join(rows)
    assert "two" in joined and "TWO" in joined and "four" in joined, joined
    assert any(r.startswith("!") for r in rows), rows
    with tempfile.TemporaryDirectory() as d:
        p1, p2 = os.path.join(d, "a.txt"), os.path.join(d, "b.txt")
        open(p1, "w").writelines(a)
        open(p2, "w").writelines(b)
        assert main(["--no-color", p1, p2]) == 1
        assert main(["--no-color", p1, p1]) == 0
    print("diffside selftest: PASS")
    return 0


if __name__ == "__main__":
    sys.exit(main())
