#!/usr/bin/env python3
import urllib.request
import urllib.error
from html.parser import HTMLParser
import sys

routes = [
    "http://localhost:8096/",
    "http://localhost:8096/about/",
    "http://localhost:8096/services/",
    "http://localhost:8096/services/floor-installation/",
    "http://localhost:8096/services/floor-refinishing/",
    "http://localhost:8096/services/floor-restoration/",
    "http://localhost:8096/services/floor-sanding/",
    "http://localhost:8096/locations/",
    "http://localhost:8096/locations/buffalo/",
    "http://localhost:8096/locations/amherst/",
    "http://localhost:8096/locations/williamsville/",
    "http://localhost:8096/locations/clarence/",
    "http://localhost:8096/locations/east-amherst/",
    "http://localhost:8096/locations/lancaster/",
    "http://localhost:8096/reviews/",
    "http://localhost:8096/blog/",
    "http://localhost:8096/contact/",
]

class LinkExtractor(HTMLParser):
    def __init__(self):
        super().__init__()
        self.links = []
    def handle_starttag(self, tag, attrs):
        if tag == 'a':
            for attr, value in attrs:
                if attr == 'href' and value:
                    self.links.append(value)

def is_internal(url):
    return url.startswith('/') or url.startswith('http://localhost:8096')

def fetch_and_parse(url):
    try:
        with urllib.request.urlopen(url, timeout=5) as resp:
            if resp.getcode() != 200:
                return [], resp.getcode()
            body = resp.read().decode('utf-8', errors='ignore')
            parser = LinkExtractor()
            parser.feed(body)
            return parser.links, 200
    except urllib.error.HTTPError as e:
        return [], e.code
    except Exception as e:
        return [], None

def check_link(url):
    try:
        with urllib.request.urlopen(url, timeout=5) as resp:
            return resp.getcode()
    except urllib.error.HTTPError as e:
        return e.code
    except Exception:
        return None

print("=" * 70)
print("TASK 1: INTERNAL LINK AUDIT")
print("=" * 70)

all_links = {}
for route in routes:
    print(f"\nFetching {route}...", end=" ")
    links, status = fetch_and_parse(route)
    if status != 200:
        print(f"FAILED (status {status})")
        continue
    print(f"OK (found {len(links)} links)")
    all_links[route] = links

internal_links = set()
for route, links in all_links.items():
    for link in links:
        if is_internal(link):
            if '#' in link:
                link = link.split('#')[0]
            if link and link != '':
                if link.startswith('/'):
                    link = 'http://localhost:8096' + link
                internal_links.add(link)

print(f"\n\nFound {len(internal_links)} unique internal links.")
print("Checking each link...")

failed_links = {}
for idx, link in enumerate(sorted(internal_links), 1):
    status = check_link(link)
    if status != 200:
        print(f"  [{idx}] {link}: {status}")
        failed_links[link] = status
    else:
        print(f"  [{idx}] {link}: 200 OK")

print("\n" + "=" * 70)
if failed_links:
    print(f"RESULT: {len(failed_links)} links returned non-200")
    for link, code in sorted(failed_links.items()):
        print(f"  {link} -> {code}")
else:
    print(f"RESULT: All {len(internal_links)} internal links returned 200")
print("=" * 70)
