#!/usr/bin/env python3
"""
Monolithic Protected File Server
================================================================================
A self-contained file hosting gateway.
- Validates access against a FOREVER STATIC password.
- Processes state metrics via lazy rotation ONLY when an attempt is made.
- Features the simplest possible in-browser file upload form.
"""

import os
import hashlib
import mimetypes
from http.server import HTTPServer, BaseHTTPRequestHandler
from urllib.parse import urlparse, parse_qs

# ── CONFIGURATION ────────────────────────────────────────────────────────────
STATIC_PASSWORD = "MyForeverSecretPassword123"  # <--- Change your static password here
SHARED_DIRECTORY = "./shared_files"
PORT = 8080

# ── LAZY ROTATING SYSTEM CORE ────────────────────────────────────────────────
class LazyLatticeEngine:
    def __init__(self):
        self.q = 8380417
        self.state_counter = 10000000

    def process_lazy_rotation(self, input_attempt: str):
        """Processes the state engine loop only on an execution attempt."""
        # Convert password attempt string into metric seed integers
        hasher = hashlib.sha256(input_attempt.encode('utf-8'))
        seed_delta = int.from_bytes(hasher.digest()[:4], byteorder='little') % 1000

        # Advance internal ring state metrics lazily
        self.state_counter = (self.state_counter + seed_delta) % self.q
        print(f"[LAZY ENGINE ROTATED] Processing completed. State Matrix Counter: {self.state_counter}")

crypto_core = LazyLatticeEngine()

# ── WEB INSTANCE MANAGER ──────────────────────────────────────────────────────
class MonolithicGateway(BaseHTTPRequestHandler):

    def log_message(self, format, *args):
        return  # Suppress generic console outputs

    def check_auth(self, query_params) -> bool:
        """Helper to extract and verify the static password."""
        client_keys = query_params.get('key', [None])
        client_key = client_keys[0] if client_keys else None

        if client_key is not None:
            # Trigger backend state tracking metrics right on attempt
            crypto_core.process_lazy_rotation(client_key)
            return client_key == STATIC_PASSWORD
        return False

    def do_GET(self):
        parsed_url = urlparse(self.path)
        query_params = parse_qs(parsed_url.query)
        current_token = query_params.get('key', [''])[0]

        # ── GATEKEEPER VALIDATION ────────────────────────────────────────────
        if not self.check_auth(query_params):
            self.send_response(401)
            self.send_header("Content-Type", "text/html")
            self.end_headers()
            self.wfile.write(f"""
            <html><body style="background:#111;color:#fff;font-family:monospace;text-align:center;padding-top:100px;">
                <h2>🔓 MONOLITH PORTAL</h2>
                <form action="/" method="GET">
                    <input type="password" name="key" placeholder="Enter Static Password" autofocus style="padding:8px;">
                    <button type="submit" style="padding:8px;">Access</button>
                </form>
            </body></html>
            """.encode())
            return

        # ── SYSTEM SERVING CORE (AUTHENTICATED) ──────────────────────────────
        requested_file = parsed_url.path.lstrip('/')

        # UI Index Dashboard & Simple Upload Form Layout
        if not requested_file:
            self.send_response(200)
            self.send_header("Content-Type", "text/html")
            self.end_headers()

            files = os.listdir(SHARED_DIRECTORY) if os.path.exists(SHARED_DIRECTORY) else []
            links = "".join([f'<li><a href="/{f}?key={current_token}" style="color:#0f0;">{f}</a></li>' for f in files])

            self.wfile.write(f"""
            <html><body style="background:#111;color:#0f0;font-family:monospace;padding:40px;">
                <h3>🔒 Secure Vault Manifest</h3>
                <hr>
                <!-- Simplest File Upload Field -->
                <h4>Upload File To Server:</h4>
                <form action="/upload?key={current_token}" method="POST" enctype="multipart/form-data">
                    <input type="file" name="vault_file" required>
                    <button type="submit">Upload</button>
                </form>
                <hr>
                <h4>Available Assets:</h4>
                <ul>{links or "<li>No files hosted yet. Use form above to seed folder.</li>"}</ul>
            </body></html>
            """.encode())
            return

        # Serve File Stream
        filepath = os.path.abspath(os.path.join(SHARED_DIRECTORY, requested_file))
        if not filepath.startswith(os.path.abspath(SHARED_DIRECTORY)) or not os.path.exists(filepath):
            self.send_response(404)
            self.end_headers()
            return

        self.send_response(200)
        mime, _ = mimetypes.guess_type(filepath)
        self.send_header("Content-Type", mime or "application/octet-stream")
        self.end_headers()
        with open(filepath, 'rb') as f:
            self.wfile.write(f.read())

    def do_POST(self):
        """Processes file uploads seamlessly."""
        parsed_url = urlparse(self.path)
        query_params = parse_qs(parsed_url.query)
        current_token = query_params.get('key', [''])[0]

        if not self.check_auth(query_params) or parsed_url.path != "/upload":
            self.send_response(401)
            self.end_headers()
            return

        # Simple Multi-part Header Form Processing
        content_length = int(self.headers['Content-Length'])
        boundary = self.headers['Content-Type'].split("=")[1].encode()

        # Read absolute binary block incoming stream data
        raw_body = self.rfile.read(content_length)

        try:
            # Breakdown raw data chunks using simple line breaks
            parts = raw_body.split(b'--' + boundary)
            for part in parts:
                if b'filename="' in part:
                    # Isolate file content lines from raw form structural text headers
                    headers, file_data = part.split(b'\r\n\r\n', 1)
                    file_data = file_data.rsplit(b'\r\n', 1)[0]

                    # Extract standard file string title labels
                    filename_start = headers.find(b'filename="') + 10
                    filename_end = headers.find(b'"', filename_start)
                    filename = headers[filename_start:filename_end].decode('utf-8')

                    # Write physical contents straight down into the file block
                    out_path = os.path.join(SHARED_DIRECTORY, os.path.basename(filename))
                    with open(out_path, 'wb') as target_out:
                        target_out.write(file_data)
                    print(f"[FILE WRITTEN] Saved object to disk: {filename}")
        except Exception as e:
            print(f"[UPLOAD REJECT] Fault processing upload content frames: {e}")

        # Instantly send user directly back into the folder view panel
        self.send_response(303)
        self.send_header('Location', f'/?key={current_token}')
        self.end_headers()

if __name__ == "__main__":
    if not os.path.exists(SHARED_DIRECTORY):
        os.makedirs(SHARED_DIRECTORY)

    server = HTTPServer(("0.0.0.0", PORT), MonolithicGateway)
    print("=========================================================")
    print(f" MONOLITH OPERATIONAL -> Listening at http://localhost:{PORT}")
    print(f" Static Lock Active. Tracking lazy rotation calculations on attempts.")
    print("=========================================================")
    try:
        server.serve_forever()
    except KeyboardInterrupt:
        server.server_close()
