#!/usr/bin/env python3
"""Lokal bro mellom InSchool Chrome-utvidelsen og OneDrive-mappen 'InSchool sync' (Mac & Windows)."""

import glob
import json
import os
import sys
from datetime import date
from http.server import BaseHTTPRequestHandler, HTTPServer

PORT = 8765


def find_sync_folder():
    if len(sys.argv) > 1 and os.path.isdir(sys.argv[1]):
        return sys.argv[1]

    home = os.path.expanduser("~")
    candidates = [
        *glob.glob(os.path.join(home, "Library", "CloudStorage", "OneDrive*", "InSchool sync")),
        *glob.glob(os.path.join(home, "OneDrive*", "InSchool sync")),
        os.path.join(home, "OneDrive", "InSchool sync"),
    ]
    for path in candidates:
        if os.path.isdir(path):
            return path
    return None


SYNC_FOLDER = find_sync_folder()


class BridgeHandler(BaseHTTPRequestHandler):
    def _cors_headers(self):
        self.send_header("Access-Control-Allow-Origin", "*")
        self.send_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
        self.send_header("Access-Control-Allow-Headers", "Content-Type")

    def do_OPTIONS(self):
        self.send_response(204)
        self._cors_headers()
        self.end_headers()

    def do_GET(self):
        if self.path == "/ping":
            self.send_response(200)
            self._cors_headers()
            self.send_header("Content-Type", "application/json")
            self.end_headers()
            self.wfile.write(json.dumps({"ok": True, "folder": SYNC_FOLDER}).encode())
            return

        if self.path == "/outlook-events":
            if not SYNC_FOLDER:
                self.send_response(404)
                self._cors_headers()
                self.end_headers()
                return
            filepath = os.path.join(SYNC_FOLDER, "outlook-events.json")
            if not os.path.isfile(filepath):
                self.send_response(404)
                self._cors_headers()
                self.end_headers()
                return
            with open(filepath, "rb") as f:
                data = f.read()
            self.send_response(200)
            self._cors_headers()
            self.send_header("Content-Type", "application/json")
            self.end_headers()
            self.wfile.write(data)
            return

        self.send_response(404)
        self._cors_headers()
        self.end_headers()

    def do_POST(self):
        if self.path == "/save-inschool":
            if not SYNC_FOLDER:
                self.send_response(500)
                self._cors_headers()
                self.end_headers()
                return
            length = int(self.headers.get("Content-Length", 0))
            body = self.rfile.read(length)
            filename = f"inschool-sync-{date.today().isoformat()}.json"
            filepath = os.path.join(SYNC_FOLDER, filename)
            with open(filepath, "wb") as f:
                f.write(body)
            self.send_response(200)
            self._cors_headers()
            self.send_header("Content-Type", "application/json")
            self.end_headers()
            self.wfile.write(json.dumps({"ok": True, "file": filepath}).encode())
            return

        self.send_response(404)
        self._cors_headers()
        self.end_headers()

    def log_message(self, format, *args):
        print(f"[InSchool Bridge] {args[0]}")


if __name__ == "__main__":
    if not SYNC_FOLDER:
        print("Fant ikke 'InSchool sync'-mappen automatisk. Kjør med: python3 local_bridge.py /sti/til/InSchool sync")
        sys.exit(1)
    print(f"InSchool lokal bro kjører på http://127.0.0.1:{PORT}")
    print(f"Bruker OneDrive-mappe: {SYNC_FOLDER}")
    HTTPServer(("127.0.0.1", PORT), BridgeHandler).serve_forever()
