#!/usr/bin/env python3

import inspect
from importlib.metadata import version

from rich._export_format import CONSOLE_SVG_FORMAT as DEFAULT
from rich.console import Console as RichConsole

from yartsu._export_format import CONSOLE_SVG_FORMAT as MODIFIED
from yartsu.console import Console as YartsuConsole

MARKDOWN_DOC = """
# Deviation From Rich

## Versions

- Rich: {rich_version}
- Yartsu: {yartsu_version}

## CONSOLE_SVG_FORMAT Diff

```diff
{export_format_diff}
```

## Console.export_svg Diff

```diff
{export_svg_diff}
```

AUTO-GENERATED by ./scripts/rich-diff"""


def unidiff_output(expected, actual):
    """
    Helper function. Returns a string containing the unified diff of two multiline strings.
    """
    # see https://stackoverflow.com/questions/845276/how-to-print-the-comparison-of-two-multiline-strings-in-unified-diff-format

    import difflib

    expected = expected.splitlines(1)
    actual = actual.splitlines(1)

    diff = difflib.unified_diff(expected, actual)

    return "".join(diff)


def main():
    print(
        MARKDOWN_DOC.format(
            rich_version=version("rich"),
            yartsu_version=version("yartsu"),
            export_format_diff=unidiff_output(DEFAULT, MODIFIED),
            export_svg_diff=unidiff_output(
                inspect.getsource(RichConsole.export_svg),
                inspect.getsource(YartsuConsole.export_svg),
            ),
        ),
    )


if __name__ == "__main__":
    main()