import os
from django.http import HttpResponse


def _static_path(rel):
    from django.conf import settings
    return os.path.join(settings.BASE_DIR, 'exams', 'static', 'exams', rel)


def service_worker(request):
    p = _static_path('sw.js')
    if not os.path.exists(p):
        return HttpResponse('SW not found', status=404)
    with open(p, 'rb') as f:
        r = HttpResponse(f.read(), content_type='application/javascript')
    r['Service-Worker-Allowed'] = '/'
    r['Cache-Control'] = 'no-cache'
    return r


def robots_txt(request):
    body = """User-agent: *
Disallow: /admin/
Disallow: /api/portal/teacher/
Allow: /api/portal/
Allow: /static/
"""
    return HttpResponse(body, content_type='text/plain')


def manifest_root(request):
    p = _static_path('manifest.json')
    if not os.path.exists(p):
        return HttpResponse('Manifest not found', status=404)
    with open(p, 'rb') as f:
        return HttpResponse(f.read(), content_type='application/manifest+json')


def icon_serve(request, filename):
    from django.http import HttpResponse, Http404
    allowed = {'icon-192.png', 'icon-512.png', 'icon-512-maskable.png'}
    if filename not in allowed:
        raise Http404('Icon not allowed')
    p = _static_path('icons/' + filename)
    if not os.path.exists(p):
        raise Http404('Icon file missing on disk')
    with open(p, 'rb') as f:
        r = HttpResponse(f.read(), content_type='image/png')
    r['Cache-Control'] = 'public, max-age=86400'
    return r
