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

pages = [
    ("http://localhost:8096/", "Home"),
    ("http://localhost:8096/services/floor-installation/", "Service: Floor Installation"),
    ("http://localhost:8096/locations/buffalo/", "Location: Buffalo"),
    ("http://localhost:8096/contact/", "Contact"),
]

class ScriptExtractor(HTMLParser):
    def __init__(self):
        super().__init__()
        self.json_ld_blocks = []
        self.in_json_ld = False
        self.script_content = ""

    def handle_starttag(self, tag, attrs):
        if tag == 'script':
            for attr, value in attrs:
                if attr == 'type' and value == 'application/ld+json':
                    self.in_json_ld = True
                    self.script_content = ""

    def handle_data(self, data):
        if self.in_json_ld:
            self.script_content += data

    def handle_endtag(self, tag):
        if tag == 'script' and self.in_json_ld:
            self.in_json_ld = False
            if self.script_content.strip():
                self.json_ld_blocks.append(self.script_content)

def fetch_page(url):
    try:
        with urllib.request.urlopen(url, timeout=5) as resp:
            if resp.getcode() != 200:
                return None, resp.getcode()
            return resp.read().decode('utf-8', errors='ignore'), 200
    except urllib.error.HTTPError as e:
        return None, e.code
    except Exception as e:
        return None, str(e)

def extract_json_ld(html):
    parser = ScriptExtractor()
    parser.feed(html)
    return parser.json_ld_blocks

print("=" * 70)
print("TASK 3: SCHEMA.ORG JSON-LD AUDIT")
print("=" * 70)

for url, label in pages:
    print(f"\n{label}")
    print(f"  URL: {url}")

    html, status = fetch_page(url)
    if status != 200:
        print(f"  STATUS: {status} - skipping")
        continue

    json_ld_blocks = extract_json_ld(html)
    if not json_ld_blocks:
        print(f"  JSON-LD: MISSING")
        continue

    print(f"  JSON-LD blocks found: {len(json_ld_blocks)}")

    for block_idx, block in enumerate(json_ld_blocks):
        try:
            data = json.loads(block)
        except json.JSONDecodeError as e:
            print(f"    Block {block_idx + 1}: INVALID JSON - {e}")
            continue

        print(f"    Block {block_idx + 1}:")

        # Check @context
        if '@context' in data:
            print(f"      @context: {data['@context']}")
        else:
            print(f"      @context: MISSING")

        # Check @type
        if '@type' in data:
            print(f"      @type: {data['@type']}")
        else:
            print(f"      @type: MISSING")

        # Check required fields
        required_fields = ['name', 'url', 'telephone', 'address']
        missing = []
        for field in required_fields:
            if field not in data:
                missing.append(field)
            else:
                val = data[field]
                if isinstance(val, dict):
                    print(f"      {field}: [object]")
                elif isinstance(val, list):
                    print(f"      {field}: [array of {len(val)}]")
                else:
                    print(f"      {field}: {val}")

        if missing:
            print(f"      MISSING FIELDS: {', '.join(missing)}")

print("\n" + "=" * 70)
print("SUMMARY")
print("=" * 70)

schema_check = {}
for url, label in pages:
    html, status = fetch_page(url)
    if status != 200:
        schema_check[label] = "UNREACHABLE"
        continue

    json_ld_blocks = extract_json_ld(html)
    if not json_ld_blocks:
        schema_check[label] = "NO JSON-LD"
    else:
        schema_check[label] = "PRESENT"

for label, result in schema_check.items():
    status_icon = "OK" if result == "PRESENT" else "FAIL"
    print(f"  {label}: {result} [{status_icon}]")

print("=" * 70)
