{ pkgs ? import <nixpkgs> {}}:

pkgs.mkShell {
  buildInputs = with pkgs; [
    # Python development environment for Chitai
    python313Full
    python313Packages.greenlet
    python313Packages.ruff
    uv

    # postgres database
    postgresql

  ];

  shellHook = ''
    # Only cd if we're not already in backend
    if [[ $(basename $(pwd)) != "backend" ]]; then
      cd backend
    fi
    BACKEND_PATH=$(pwd)
    
    echo "Initializing Python development environment with uv"
    
    # Create a virtual environment if it doesn't exist
    if [ ! -d ".venv" ]; then
      echo "Creating virtual environment..."
      uv venv .venv
    fi
    
    # Activate the virtual environment
    source .venv/bin/activate
    
    echo "Python environment ready!"
    echo "Python version: $(python --version)"
    echo "uv version: $(uv --version)"
    echo "Virtual environment activated at: $VIRTUAL_ENV"
    
    # Install required packages
    uv sync
    echo "Successfully installed packages!"
    
    echo "Setting up the postgres database"
    export PGHOST=$BACKEND_PATH/.postgres
    export PGDATA=$PGHOST/data
    export PGDATABASE=chitai
    export PGUSERNAME=chitai_user
    export PGPASSWORD="chitai_password"
    export PGLOG=$PGHOST/postgres.log
    export LD_LIBRARY_PATH="${pkgs.postgresql.lib}/lib:$LD_LIBRARY_PATH"
    
    mkdir -p $PGHOST
    
    # Initialize the postgres database if not present
    if [ ! -d "$PGDATA" ]; then
      echo "Initializing PostgreSQL..."
      initdb -D $BACKEND_PATH/.postgres/data \
        -U $PGUSERNAME \
        --pwfile=<(echo "$PGPASSWORD") \
        --auth=md5 \
        --encoding=UTF-8
    fi
    
    if ! pg_ctl status > /dev/null 2>&1
    then
      echo "Starting PostgreSQL..."
      pg_ctl start -l $PGLOG -o "--unix_socket_directories='$PGHOST'"
    fi
    
    echo "PostgreSQL is running!"
    
    if ! psql -h $PGHOST -d postgres -lqt 2>/dev/null | cut -d \| -f 1 | grep -qw chitai; then
      echo "Creating database chitai..."
      createdb -U $PGUSERNAME -h $PGHOST chitai
    fi

    # Run database migrations
    uv run alchemy --config chitai.database.config.config upgrade --no-prompt
    
    # Return to root directory
    cd -
  '';

  exitHook = ''
    BACKEND_PATH=$(pwd)/backend
    cd $BACKEND_PATH
    echo "Stopping PostgreSQL..."
    pg_ctl stop
    cd -
  '';
}
