"""Rewrite app links without reserializing unrelated HTML or scripts."""
from html import escape
from html.parser import HTMLParser
import posixpath
from urllib.parse import parse_qsl, quote, unquote, urlencode, urlsplit


def rewrite_html_links(markup, *, site_url, repository=None, readme_path="", ref_query=""):
    site = urlsplit(site_url)
    ref_params = parse_qsl(ref_query, keep_blank_values=True)
    line_offsets = [0]
    for line in markup.split('\n')[:-1]:
        line_offsets.append(line_offsets[-1] + len(line) + 1)
    patches = []

    class Links(HTMLParser):
        def handle_starttag(self, tag, attributes):
            key = 'href' if tag == 'a' else 'src' if tag == 'img' else None
            if not key:
                return
            attrs = dict(attributes)
            address = attrs.get(key)
            if not address:
                return
            try:
                url = urlsplit(address.strip())
            except ValueError:
                return
            if repository and not url.scheme and not url.netloc and url.path:
                path = unquote(url.path)
                base = '' if path.startswith('/') else posixpath.dirname(readme_path)
                path = posixpath.normpath('/' + posixpath.join(base, path.lstrip('/'))).lstrip('/')
                route = 'raw' if tag == 'img' else 'src'
                target = f"{repository}/{route}" + ('/' + quote(path, safe='/') if path else '')
                params = [(k, v) for k, v in parse_qsl(url.query, keep_blank_values=True)
                          if k not in {'ref', 'ref_type', 'ref_value'}]
                query = urlencode(params + ref_params)
                attrs[key] = target + ('?' + query if query else '') + ('#' + url.fragment if url.fragment else '')
            if tag == 'a' and url.netloc and url.scheme.lower() in {'', 'http', 'https'} and url.netloc.lower() != site.netloc.lower():
                attrs['target'] = '_blank'
                rel = list(dict.fromkeys((attrs.get('rel') or '').split() + ['noopener', 'noreferrer']))
                attrs['rel'] = ' '.join(rel)
            if attrs == dict(attributes):
                return
            raw = self.get_starttag_text()
            closing = ' />' if raw.endswith('/>') else '>'
            replacement = '<' + tag + ''.join(
                ' ' + name + ('="' + escape(value, quote=True) + '"' if value is not None else '')
                for name, value in attrs.items()
            ) + closing
            line, column = self.getpos()
            start = line_offsets[line - 1] + column
            patches.append((start, start + len(raw), replacement))

        handle_startendtag = handle_starttag

    parser = Links(convert_charrefs=False)
    parser.feed(markup)
    parser.close()
    chunks = []
    cursor = 0
    for start, end, replacement in patches:
        chunks.extend((markup[cursor:start], replacement))
        cursor = end
    chunks.append(markup[cursor:])
    return ''.join(chunks)
