import parsel
import httpx
from pathlib import Path
from textwrap import indent
from subprocess import Popen, PIPE

VERSION = '0.31.2'

CACHE = Path('.spec', VERSION)
URL = f'https://spec.commonmark.org/{VERSION}/'

if CACHE.exists():
    sel = parsel.Selector(CACHE.read_text())
else:
    response = httpx.get('https://spec.commonmark.org/0.31.2/')
    response.raise_for_status()
    CACHE.parent.mkdir(parents=True, exist_ok=True)
    CACHE.write_text(response.text)
    sel = parsel.Selector(response.text)


formatter = Popen(['zig', 'fmt', '--stdin'], stdin=PIPE, encoding='utf-8')
assert formatter.stdin

write = formatter.stdin.write

write(f'''
    //! Example cases from Commonmark spec {VERSION}
    //! {URL}

    const std = @import("std");
    const convert = @import("main.zig").convert;
''')

for example in sel.css('.example'):
    name = example.css('.examplenum > a::text').get()

    md = ''.join(example.css('.language-markdown *::text').getall())
    html = ''.join(example.css('.language-html *::text').getall())

    md = md.replace('→', '    ')
    html = html.replace('→', '    ')

    assert name is not None

    write(f'''
        test "{name}" {{
            const output = try convert(std.testing.allocator,
                {indent(md, r'\\', lambda _: True) if md else '""'}
            );
            defer std.testing.allocator.free(output);

            try std.testing.expectEqualStrings(
                {indent(html, r'\\', lambda _: True) if html else '""'}
                ,
                output
            );
        }}
    ''')

formatter.stdin.close()
