#!/usr/bin/env python3
"""
Fallback terminal analyzer for Namecheap Python.
Static public HTML/JS analysis only.
"""
import argparse, base64, json, re, socket, ipaddress
from html.parser import HTMLParser
from urllib.parse import urljoin, urlparse, unquote
from urllib.request import Request, urlopen

MEDIA_RE = re.compile(r'https?://[^\s"\'<>\\]+?\.(?:m3u8|mpd|mp4|webm|m4v|mov|mkv|m4s|ts|aac|mp3)(?:\?[^\s"\'<>\\]*)?', re.I)

def public_host(host):
    for info in socket.getaddrinfo(host, None):
        if not ipaddress.ip_address(info[4][0]).is_global:
            return False
    return True

def fetch(url, limit=3_000_000):
    p = urlparse(url)
    if p.scheme not in ('http','https') or not p.hostname or not public_host(p.hostname):
        raise ValueError('Only public HTTP/HTTPS URLs are allowed')
    r = urlopen(Request(url, headers={'User-Agent':'ShortSeris-Python-Analyzer/1.0'}), timeout=20)
    data = r.read(limit+1)
    if len(data) > limit:
        raise ValueError('Response too large')
    return r.geturl(), dict(r.headers.items()), data.decode('utf-8','replace')

class P(HTMLParser):
    def __init__(self):
        super().__init__()
        self.scripts=[]
    def handle_starttag(self, tag, attrs):
        d=dict(attrs)
        if tag.lower()=='script' and d.get('src'):
            self.scripts.append(d['src'])

def main():
    ap=argparse.ArgumentParser()
    ap.add_argument('url')
    args=ap.parse_args()

    final, headers, html = fetch(args.url)
    found=set(MEDIA_RE.findall(html))
    parser=P()
    parser.feed(html)

    for src in parser.scripts[:25]:
        try:
            jsurl=urljoin(final,src)
            _,_,js=fetch(jsurl, 2_000_000)
            found.update(MEDIA_RE.findall(js))
        except Exception:
            pass

    print(json.dumps({
        'final_url': final,
        'sources': sorted(found)
    }, indent=2))

if __name__=='__main__':
    main()
