# Copyright 2025 Pasteur Labs. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0

import os
import pwd

from pydantic import BaseModel

# Create this directory at import time (i.e. once at build time via the sanity
# check step in Dockerfile.base); any later user should be able to read/write it
_SOME_DIR = "/home/tesseract-user/.somedir"
os.makedirs(_SOME_DIR, exist_ok=True)

#
# Schemas
#


class InputSchema(BaseModel):
    pass


class OutputSchema(BaseModel):
    uid: int
    gid: int
    username: str
    home: str
    shell: str
    somedir_readable: bool
    somedir_writable: bool
    hello_dir_created: bool


#
# Required endpoints
#


def apply(inputs: InputSchema) -> OutputSchema:
    """A simple Tesseract that fails if the current OS user doesn't have a valid /etc/passwd entry."""
    # Get current user ID
    uid = os.getuid()
    gid = os.getgid()

    # Try to get the passwd entry for the current user
    try:
        pw_entry = pwd.getpwuid(uid)
    except KeyError as exc:
        raise RuntimeError(
            f"Current user (UID: {uid}) does not have an entry in /etc/passwd. "
            "This container's entrypoint should have set up libnss_wrapper with a passwd entry for this UID."
        ) from exc

    if pw_entry.pw_gid != gid:
        raise RuntimeError(
            f"Current group (GID: {gid}) does not match expected group from /etc/passwd ({pw_entry.pw_gid})."
        )

    # Check read/write permissions on the pre-created directory
    somedir_readable = os.access(_SOME_DIR, os.R_OK)
    somedir_writable = os.access(_SOME_DIR, os.W_OK)

    # Try to create a subfolder to confirm write access is real
    hello_dir = os.path.join(_SOME_DIR, "hello")
    try:
        os.makedirs(hello_dir, exist_ok=True)
        hello_dir_created = True
    except OSError:
        hello_dir_created = False

    # Return the user information
    return OutputSchema(
        uid=pw_entry.pw_uid,
        gid=pw_entry.pw_gid,
        username=pw_entry.pw_name,
        home=pw_entry.pw_dir,
        shell=pw_entry.pw_shell,
        somedir_readable=somedir_readable,
        somedir_writable=somedir_writable,
        hello_dir_created=hello_dir_created,
    )
