#!/usr/bin/env python3
"""Manifest, pictogrammen en service worker, met de juiste scope onder /verhaaltjesboek/."""
import json
import os
import re
import socket
import struct
import subprocess
import tempfile
import time
import urllib.error
import urllib.request
from pathlib import Path

WEB = Path(__file__).resolve().parents[1]
ROOT = WEB.parent
PREFIX = '/verhaaltjesboek'
checks = 0

def check(value, label):
    global checks
    checks += 1
    assert value, label

def png_size(path):
    data = path.read_bytes()
    check(data.startswith(b'\x89PNG\r\n\x1a\n') and data[12:16] == b'IHDR', f'{path.name} is een PNG')
    return struct.unpack('>II', data[16:24])

manifest = json.loads((WEB / 'manifest.webmanifest').read_text())
check(manifest['name'] == 'Verhalenboek' and manifest['short_name'] == 'Verhalenboek', 'Naam van de webapp')
check(manifest['lang'] == 'nl' and manifest['display'] == 'standalone', 'Taal en standalone-weergave')
check(manifest['start_url'] == PREFIX + '/' and manifest['scope'] == PREFIX + '/', 'start_url en scope blijven in de submap')
check(manifest['id'] == PREFIX + '/', 'App-id blijft de submap')
check(manifest['start_url'].startswith(manifest['scope']), 'start_url valt binnen scope')
check(manifest['theme_color'] == '#f4efe6' and manifest['background_color'] == '#f4efe6', 'Kleuren volgen de pagina')
icons = {(icon['sizes'], icon['purpose']): icon for icon in manifest['icons']}
for size, purpose in [('192x192', 'any'), ('512x512', 'any'), ('192x192', 'maskable'), ('512x512', 'maskable')]:
    icon = icons.get((size, purpose))
    check(icon is not None, f'Icoon {size} ({purpose})')
    check(icon['src'].startswith(PREFIX + '/assets/'), f'Icoonpad blijft in de submap: {icon["src"]}')
    file = WEB / icon['src'].removeprefix(PREFIX + '/')
    check(file.is_file() and png_size(file) == tuple(int(part) for part in size.split('x')), f'{file.name} is {size}')

check(png_size(WEB / 'assets/apple-touch-icon.png') == (180, 180), 'apple-touch-icon is 180')
check(png_size(WEB / 'assets/favicon-32.png') == (32, 32), 'favicon-32 is 32')
svg = (WEB / 'assets/favicon.svg').read_text()
check('f4a261' in svg.lower() and '3f63d4' in svg.lower(), 'Favicon blijft een blauw boek met oranje bladwijzer')
check('<svg' in (WEB / 'assets/mask-icon.svg').read_text(), 'mask-icon is svg')

worker = (WEB / 'sw.js').read_text()
check("request.method !== 'GET'" in worker, 'Service worker laat schrijfacties met rust')
check('api' in worker and 'auth' in worker and 'callback' in worker, 'Service worker slaat api en login over')
check('wiki' in worker and '/api.php/wiki/' in worker, 'Service worker noemt wiki-schrijfacties via api.php')
check('PATCH' in worker and "request.method !== 'GET'" in worker, 'Service worker noemt PATCH en onderschept die methode niet')
htaccess = (WEB / '.htaccess').read_text()
check(re.search(r'(?i)<\s*/?\s*Limit', htaccess) is None, '.htaccess beperkt geen HTTP-methode')
router_src = (WEB / 'router.php').read_text()
check('REQUEST_METHOD' not in router_src, 'De ontwikkelrouter filtert geen HTTP-methode')
wiki_bypass = re.compile(r'/(?:api|auth|callback)\.php(?:/|$)', re.I)
check(wiki_bypass.search('/verhaaltjesboek/api.php/wiki/pages') and wiki_bypass.search('/verhaaltjesboek/api.php/wiki/categories'), 'Wiki-API valt onder de api.php-uitsluiting')
check(worker.index("request.method !== 'GET'") < worker.index('function bypass'), 'Een schrijfactie komt niet in de cache terecht')
check("pathname.endsWith('/sw.js')" in worker, 'Service worker cachet zichzelf niet')
registrar = (WEB / 'assets/pwa.js').read_text()
check("new URL('sw.js', scope)" in registrar and 'scope: scope.href' in registrar, 'Registratie gebruikt de map van de pagina')

router = r'''<?php
declare(strict_types=1);
$root = getenv('VERHALENBOEK_WEBROOT');
$prefix = '/verhaaltjesboek';
$path = rawurldecode(parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH) ?: '/');
if ($path === $prefix) {
    header('Location: '.$prefix.'/');
    return true;
}
if (!is_string($root) || $root === '' || !str_starts_with($path, $prefix.'/')) {
    http_response_code(404);
    header('Content-Type: text/plain; charset=utf-8');
    echo 'Niet gevonden';
    return true;
}
$rel = substr($path, strlen($prefix));
if (preg_match('#^/api\.php(?:/|$)#', $rel)) {
    $_SERVER['SCRIPT_NAME'] = $prefix.'/api.php';
    require $root.'/api.php';
    return true;
}
if ($rel === '/' || $rel === '') {
    $_SERVER['SCRIPT_NAME'] = $prefix.'/index.php';
    require $root.'/index.php';
    return true;
}
$file = $root.$rel;
if (str_ends_with(strtolower($rel), '.php') && is_file($file)) {
    $_SERVER['SCRIPT_NAME'] = $prefix.$rel;
    require $file;
    return true;
}
if (is_file($file)) {
    $extension = strtolower(pathinfo($file, PATHINFO_EXTENSION));
    $type = match ($extension) {
        'webmanifest' => 'application/manifest+json; charset=utf-8',
        'js' => 'application/javascript; charset=utf-8',
        'css' => 'text/css; charset=utf-8',
        'svg' => 'image/svg+xml',
        'png' => 'image/png',
        default => 'application/octet-stream',
    };
    header('Content-Type: '.$type);
    if ($extension === 'webmanifest' || basename($file) === 'sw.js') header('Cache-Control: no-cache');
    readfile($file);
    return true;
}
http_response_code(404);
header('Content-Type: text/plain; charset=utf-8');
echo 'Niet gevonden';
return true;
'''

def free_port():
    with socket.socket() as sock:
        sock.bind(('127.0.0.1', 0))
        return sock.getsockname()[1]

def wait_for(url):
    for _ in range(100):
        try:
            urllib.request.urlopen(url).close()
            return
        except urllib.error.URLError:
            time.sleep(0.05)
    raise RuntimeError('server startte niet: ' + url)

def fetch(url, method='GET', data=None, headers=None):
    request = urllib.request.Request(url, data=data, headers=headers or {}, method=method)
    try:
        response = urllib.request.urlopen(request)
    except urllib.error.HTTPError as error:
        response = error
    with response:
        body = response.read()
        return response.status, {key.lower(): value for key, value in response.headers.items()}, body

with tempfile.TemporaryDirectory(prefix='pwa-', dir=WEB / 'tests/artifacts') as tmp:
    tmp_path = Path(tmp)
    (tmp_path / 'data').mkdir()
    router_path = tmp_path / 'router.php'
    router_path.write_text(router)
    port = free_port()
    base = f'http://127.0.0.1:{port}{PREFIX}'
    log = (tmp_path / 'server.log').open('w')
    process = subprocess.Popen(
        ['php', '-d', 'opcache.enable=0', '-S', f'127.0.0.1:{port}', '-t', str(tmp_path), str(router_path)],
        stdout=log, stderr=log, start_new_session=True,
        env={**os.environ, 'VERHALENBOEK_DATA_DIR': str(tmp_path / 'data'), 'VERHALENBOEK_WEBROOT': str(WEB)},
    )
    try:
        wait_for(base + '/')
        status, headers, body = fetch(base + '/manifest.webmanifest')
        check(status == 200 and headers.get('content-type', '').startswith('application/manifest+json'), 'Manifest heeft het juiste type')
        served = json.loads(body)
        check(served['start_url'] == PREFIX + '/' and served['scope'] == PREFIX + '/', 'Geserveerd manifest blijft in de submap')
        status, headers, html = fetch(base + '/')
        page = html.decode()
        check(status == 200 and '<title>Verhalenboek</title>' in page, 'Startpagina onder de submap')
        check('rel="manifest" href="manifest.webmanifest"' in page, 'Manifestlink is relatief')
        check('href="/manifest' not in page and 'href="/assets/' not in page and 'src="/' not in page, 'Geen absolute paden vanaf de domeinwortel')
        check('apple-mobile-web-app-capable' in page and 'apple-mobile-web-app-title' in page and 'Verhalenboek' in page, 'iOS-meta voor toevoegen aan beginscherm')
        check('assets/apple-touch-icon.png' in page and 'assets/favicon.svg' in page and 'assets/pwa.js' in page, 'Favicon, aanraakicoon en registratie')
        check('name="theme-color"' in page and '#f4efe6' in page, 'Thema-kleur')
        check(page.index('>Overzicht<') < page.index('>Wiki<') < page.index('>Instellingen<'), 'Wiki staat in het menu naast Overzicht')
        for name in ['icon-192.png', 'icon-512.png', 'icon-maskable-512.png', 'apple-touch-icon.png', 'favicon.svg']:
            status, headers, payload = fetch(base + '/assets/' + name)
            check(status == 200 and len(payload) > 32, name + ' is bereikbaar')
        status, headers, script = fetch(base + '/sw.js')
        check(status == 200 and b"method !== 'GET'" in script and headers.get('content-type', '').startswith('application/javascript'), 'Service worker onder de submap')
        status, _, me = fetch(base + '/api.php/me', headers={'Accept': 'application/json'})
        profile = json.loads(me)
        check(status == 200 and profile['user']['name'] == 'test_user_1', 'API GET onder de submap blijft werken')
        status, _, denied = fetch(
            base + '/api.php/days',
            method='POST',
            data=b'{}',
            headers={'Accept': 'application/json', 'Content-Type': 'application/json'},
        )
        check(status == 403 and 'Ongeldige sessie' in json.loads(denied)['error'], 'API POST onder de submap blijft naar PHP gaan')
        status, _, wiki_denied = fetch(
            base + '/api.php/wiki/categories',
            method='POST',
            data=b'{"title":"Plekken"}',
            headers={'Accept': 'application/json', 'Content-Type': 'application/json'},
        )
        check(status == 403 and 'Ongeldige sessie' in json.loads(wiki_denied)['error'], 'Wiki-schrijven onder de submap blijft naar PHP gaan')
        status, _, wiki_patch = fetch(
            base + '/api.php/wiki/pages/oude-plein',
            method='PATCH',
            data=b'{"title":"Plein"}',
            headers={'Accept': 'application/json', 'Content-Type': 'application/json'},
        )
        check(status == 403 and 'Ongeldige sessie' in json.loads(wiki_patch)['error'], 'PATCH onder de submap bereikt PHP')
        status, doc_headers, docs = fetch(base + '/docs.php')
        check(status == 200 and 'rel="manifest" href="manifest.webmanifest"' in docs.decode(), 'Documentatie deelt het manifest')
    finally:
        process.kill()
        process.wait(timeout=5)
        log.close()

root_port = free_port()
with tempfile.TemporaryDirectory(prefix='pwa-root-', dir=WEB / 'tests/artifacts') as tmp:
    env = {**os.environ, 'VERHALENBOEK_DATA_DIR': str(Path(tmp) / 'data')}
    Path(tmp, 'data').mkdir()
    log = Path(tmp, 'server.log').open('w')
    process = subprocess.Popen(
        ['php', '-d', 'opcache.enable=0', '-S', f'127.0.0.1:{root_port}', '-t', str(WEB), str(WEB / 'router.php')],
        stdout=log, stderr=log, start_new_session=True, env=env,
    )
    try:
        wait_for(f'http://127.0.0.1:{root_port}/')
        status, headers, body = fetch(f'http://127.0.0.1:{root_port}/manifest.webmanifest')
        check(status == 200 and headers.get('content-type', '').startswith('application/manifest+json'), 'Lokale router zet het manifest-type')
        check(b'"scope"' in body, 'Lokale router levert het manifest')
    finally:
        process.kill()
        process.wait(timeout=5)
        log.close()

print(f'PWA: {checks} controles geslaagd.')
