"""Inspect a saved HTML file without making requests or executing scripts.

Usage: python3 link_source_audit.py page.html https://source.example/page https://target.example/
This is document evidence, not an availability, Google-index or safety check.
"""
from html.parser import HTMLParser
import json
from pathlib import Path
import sys
from urllib.parse import urljoin, urldefrag


class Document(HTMLParser):
    def __init__(self):
        super().__init__(convert_charrefs=True)
        self.anchors, self.directives, self.canonicals = [], [], []
        self.base = None

    def handle_starttag(self, tag, attrs):
        attrs = dict(attrs)
        if tag == 'base' and self.base is None and attrs.get('href'):
            self.base = attrs['href']
        if tag == 'a' and attrs.get('href'):
            self.anchors.append({'href': attrs['href'], 'rel': attrs.get('rel', '')})
        if tag == 'meta' and attrs.get('name', '').lower() in ('robots', 'googlebot'):
            self.directives.append({'name': attrs['name'].lower(), 'content': attrs.get('content', '')})
        if tag == 'link' and 'canonical' in attrs.get('rel', '').lower().split():
            self.canonicals.append(attrs.get('href', ''))


def inspect_html(html, source_url, target_url):
    parser = Document()
    parser.feed(html)
    base = urljoin(source_url, parser.base) if parser.base else source_url
    target = urldefrag(target_url)[0]
    matches = [{**row, 'resolved_href': urldefrag(urljoin(base, row['href']))[0]}
               for row in parser.anchors
               if urldefrag(urljoin(base, row['href']))[0] == target]
    tokens = {x.strip().lower() for row in parser.directives
              for x in row['content'].replace(',', ' ').split()}
    return {'target_url': target_url, 'target_anchor_present': bool(matches),
            'matching_anchors': matches, 'document_directives': parser.directives,
            'document_noindex': bool(tokens & {'noindex', 'none'}),
            'canonical_hrefs': [urljoin(base, x) for x in parser.canonicals],
            'scope': 'Saved HTML anchors only; fragments ignored, queries preserved. No HTTP/header/robots.txt/JavaScript or Google index verification.'}


def examples():
    return [{'case': label, **inspect_html(body, 'https://source.example/page', 'https://target.example/')}
            for label, body in (
                ('link_present', '<a href="https://target.example/">資料</a>'),
                ('body_replaced', '<h1>Account disabled</h1>'),
                ('noindex_but_link_present', '<meta name="robots" content="noindex,nofollow"><a href="https://target.example/" rel="nofollow">資料</a>'),
            )]


if __name__ == '__main__':
    if len(sys.argv) != 4:
        raise SystemExit('Usage: python3 link_source_audit.py page.html SOURCE_URL TARGET_URL')
    print(json.dumps(inspect_html(Path(sys.argv[1]).read_text(encoding='utf-8'), *sys.argv[2:]), ensure_ascii=False, indent=2))
