#!/usr/bin/env python3
"""Streams an uploaded connex photo. GET ?id=<photo_id>.

Auth-gated (page_key 'connex'). Photos live under /opt/ngon/data (outside
DocumentRoot), so they can't be served statically — this CGI reads the row,
resolves the file, and streams the bytes.
"""

import cgi
import os
import sys

sys.path.insert(0, '/opt/ngon/apps')
sys.path.insert(0, '/var/www/html/ngon/connex')
from managers.auth_manager import AuthManager
from connex_db import get_db, PHOTO_DIR


def fail(status="404 Not Found"):
    sys.stdout.write(f"Status: {status}\r\n")
    sys.stdout.write("Content-Type: text/plain\r\n\r\n")
    sys.stdout.write("not found")


def main():
    form = cgi.FieldStorage()
    auth = AuthManager('connex')
    username = auth.is_authenticated()
    if not username or not auth.check_access(username):
        fail("403 Forbidden")
        return

    try:
        pid = int(form.getvalue('id'))
    except (TypeError, ValueError):
        fail("400 Bad Request")
        return

    conn = get_db()
    row = conn.execute("SELECT container_id, filename FROM photos WHERE id=?", (pid,)).fetchone()
    conn.close()
    if not row:
        fail()
        return

    path = os.path.join(PHOTO_DIR, str(row['container_id']), row['filename'])
    if not os.path.isfile(path):
        fail()
        return

    with open(path, 'rb') as f:
        data = f.read()

    out = sys.stdout.buffer
    sys.stdout.write("Content-Type: image/jpeg\r\n")
    sys.stdout.write(f"Content-Length: {len(data)}\r\n")
    sys.stdout.write("Cache-Control: private, max-age=86400\r\n\r\n")
    sys.stdout.flush()
    out.write(data)
    out.flush()


if __name__ == "__main__":
    main()
