"""Serve only the supplied sample course with a local SCORM API and no external network."""
from functools import partial
from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from tempfile import TemporaryDirectory
import zipfile

HARNESS = '''<!doctype html><html><head><meta charset="utf-8"><title>H5P offline SCORM harness</title></head><body>
<p>SCORM 1.2 review API · external requests blocked by CSP</p>
<button onclick="sessionStorage.removeItem('h5p-review');location.reload()">Reset learner</button>
<pre id="state"></pre><script>
const values=JSON.parse(sessionStorage.getItem('h5p-review')||'{}');
window.API={LMSInitialize:()=> 'true',LMSFinish:()=> 'true',
LMSGetValue:key=>values[key]||'',
LMSSetValue:(key,value)=>{values[key]=value;document.getElementById('state').textContent=JSON.stringify(values,null,2);return 'true';},
LMSCommit:()=>{sessionStorage.setItem('h5p-review',JSON.stringify(values));return 'true';},
LMSGetLastError:()=> '0',LMSGetErrorString:()=> '',LMSGetDiagnostic:()=> ''};
</script><iframe title="SCORM course" src="index.html" style="width:100%;height:850px;border:0"></iframe></body></html>'''


class Handler(SimpleHTTPRequestHandler):
    def end_headers(self):
        self.send_header('Content-Security-Policy', "default-src 'self' data: blob:; script-src 'self' 'unsafe-inline' 'unsafe-eval'; style-src 'self' 'unsafe-inline'; font-src 'self' data:; img-src 'self' data: blob:; connect-src 'self'")
        super().end_headers()


if __name__ == '__main__':
    archive = Path(__file__).resolve().parent / 'h5p-eight-type-sample-scorm.zip'
    with TemporaryDirectory(prefix='docudeck-h5p-review-') as folder:
        root = Path(folder).resolve()
        with zipfile.ZipFile(archive) as package:
            for entry in package.infolist():
                target = (root / entry.filename).resolve()
                if not target.is_relative_to(root):
                    raise ValueError('Unsafe ZIP path')
            package.extractall(root)
        (root / 'harness.html').write_text(HARNESS, encoding='utf-8')
        print('Review: http://127.0.0.1:4179/harness.html (Ctrl+C to stop)')
        with ThreadingHTTPServer(('127.0.0.1', 4179), partial(Handler, directory=str(root))) as server:
            try:
                server.serve_forever()
            except KeyboardInterrupt:
                pass
